【问题标题】:how to differentiate integer pointer and integer array pointer如何区分整数指针和整数数组指针
【发布时间】:2016-01-11 00:49:26
【问题描述】:

我试图区分整数指针和整数数组指针,这是我用作示例的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ZLEN 5
typedef int zipdig[ZLEN] ;
#define UCOUNT 3
typedef int (*row5_pt)[ZLEN];

int main(int argc, char *argv[]) {
    zipdig cmu = {8, 5, 2, 1, 3};
    zipdig mit = {0, 2, 1, 3, 9};
    zipdig ucb = {9, 4, 7, 2, 0};

    int *univ[UCOUNT] = {mit, cmu, ucb};
    int result1 = *univ[1];

    row5_pt pt[UCOUNT] = {&mit, &cmu, &ucb};

    int result2 = (*pt[1])[1];

    printf("\nresult is %d \n", result1);
    printf("\nthe size of dereferenced univ is %lu bytes \n", sizeof(*univ[1]));

    printf("\nresult is %d \n", result2);
    printf("\nthe size of dereferenced pt is %lu bytes \n", sizeof(*pt[1]));


    return 0;
}

起初我对以下两个作业感到困惑:

int *univ[UCOUNT] = {mit, cmu, ucb};
row5_pt pt[UCOUNT] = {&mit, &cmu, &ucb};

这里的 univ 是一个由 3 个整数指针组成的数组,而 pt 是一个指向一个 5 元素 int 数组的指针数组。而我的疑惑是,在第一次赋值时,mit、cmu、ucb这些数组标识都被当成指针,但是到了第二次赋值的时候,为什么mit、cmu和ucb被当成数组,而不是指针呢?

后来才知道,这是因为我使用的指针类型不同:第一次赋值,univ的元素是一个整型指针,而mit、cmu、ucb正好是整型指针,但是对于第二次赋值, pt的元素是指向数组的指针,不是整数,因此不能直接使用mit、cmu或ucb,而必须使用它们的地址。

我的理解正确吗?

【问题讨论】:

    标签: c pointers


    【解决方案1】:

    是的,你的理解是正确的。

    原因是所涉及的指针的类型&amp;mit 是指向数组的指针,而 mit(在表达式中)被转换为指向数组第一个元素的指针。

    int a[10];
    int *p = a; // 'a' decays into a pointer to its first element i.e. &a[0]
    int *q = &a[0]; // Equivalent to the above
    
    int (*x)[10] = &a; // &a is of type int(*)[10] i.e. a pointer to an array of 10 ints
    

    另见:What is array decaying?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 2017-01-30
      • 2019-10-27
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多