简体   繁体   English

C语言编程。 指针数组和指向数组的指针

[英]C programming. Array of pointers, and pointer to an array

Why I'm getting compiling error in following code? 为什么在以下代码中出现编译错误? and What is the difference between int (*p)[4] , int *p[4] , and int *(p)[4] ? int (*p)[4]int *p[4]int *(p)[4]什么区别?

#include <stdio.h>
int main(){
   int (*p)[4];// what is the difference between int (*p)[4],int *p[4], and int *(p)[4]
   int x=0;
   int y=1;
   int z=2;
   p[0]=&x;
   p[1]=&y;
   p[2]=&z;
   for(int i=0;i<3;++i){
      printf("%i\n",*p[i]);
   }
   return 0;
}

There is no difference between 两者之间没有区别

int *p[4];

and

int *(p)[4];

Both declare p to be an array of 4 pointers. 两者都声明p为4个指针的数组。

int x;
p[0] = &x;

is valid for both. 对两者均有效。

int (*p)[4];

declares p to be a pointer to an array of 4 int s. 声明p为指向4个int s数组的指针。

You can get more details on the difference between 您可以了解更多有关以下内容的详细信息

int *p[4];
int (*p)[4];

at C pointer to array/array of pointers disambiguation . C指向数组的指针/消除歧义的数组

  • int (*p)[4] : (*p) is an array of 4 int => p pointer to an array (array of 4 int ) int (*p)[4](*p)是4个int的数组=> p指向数组的指针(4个int数组)
  • int *p[4] = int * p[4] : p is an array of 4 int * int *p[4] = int * p[4]p是4个int *的数组int *
  • int *(p)[4] : same as the second int *(p)[4] :与第二个相同

In your case, you should the second form. 对于您的情况,您应该使用第二种形式。

This is array of 4 pointers: int *p[4] . 这是4个指针的数组: int *p[4] So array will have 4 pointers, they point to int value. 因此数组将具有4个指针,它们指向int值。 This is the same int *(p)[4] . 这与int *(p)[4]

As for int (*p)[4]; 至于int (*p)[4]; this is pointer to an array of 4 integers. 这是指向4个整数的数组的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM