关于数组和指针混合的声明

about the declaration of a mixture of array and pointer

本文关键字:指针 混合 声明 于数组 数组      更新时间:2023-10-16

谁能解释一下声明数组和指针混合的规则?

下面是我的发现。但是,我不明白为什么int *p[10]表示an allocation of 10 consecutive memory blocks (each can store data of type int *),而int (*p)[10]表示declaring a pointer to an array of 10 consecutive memory blocks (each can store data of type int)。这些代码背后的规则是什么?

int p[10];     //10 consecutive memory blocks (each can store data of type int) are allocated and named as p
int *p[10];    //10 consecutive memory blocks (each can store data of type int *) are allocated and named as p
int (*p)[10];  //p is a pointer to an array of 10 consecutive memory blocks (each can store data of type int)

目前,我猜规则是:

xxx[10]将被解释为please allocating 10 memory blocks in which each blocks may store xxx。因此,int *p[10]会得到10 memory blocks in which each can store data of type int *;

由于()

(*p)将首先被解释,这将导致指向某个地方的指针。因此,int (*p)[10]将得到a pointer to an array of 10 consecutive memory blocks (each can store data of type int)

对不起,我的英语不好。希望你们能理解我的意思。任何帮助都是感激的!非常感谢!

C使用中缀符号表示类型。一个包含10个int类型的数组的类型是int [10],但是任何从数组类型派生的,其派生都在int[10]之间(不像在其他语言中那样在末尾)。

如果我们声明了一个具有这种类型的变量,它不是int [10] arr;,而是int arr [10];

同样,指向10个int型数组的指针不是int [10] *,而是int (*) [10]

需要()的原因是int * [10]将是一个包含10个int *的数组。()有分解int*的作用,所以它不能被解析为int *类型。除此之外,它们没有"任何意义"。

你实际上已经引用了规则。唯一需要补充的是,您最好这样写:

int* p[10]; 
   ^------ belongs to int
int (*p)[10];
     ^---- belongs to p, ie p is pointer to int[10]

如果您不确定,您可以随时查看http://cdecl.org/

PS:实际上,从语法上讲,写(1)比写(2)更有意义:

int *a;  // (1)
int* a;  // (2)

因为声明两个指针必须这样写:

int *a,*b;    // and not  int *a,b; !!

然而,从语义上讲,*是类型的一部分,即。(1)和(2)都声明了一个名为a(int*),用(2)来表达更清楚。因此,多个指针的声明通常放在单独的行上:

int* a;
int* b;