不理解*p [3]和(*p)[3]之间的区别

opu*_*u 웃 2 c pointers

在我的书中,有人写过*p[3] declares p as an array of 3 pointers.我知道了.但对于(*p)[3],已有人写过(*p)[3] declares p as a pointer to an array of three elements.这是什么意思?(*p)[3]没有例子.任何人都可以给我一个例子吗?

Rah*_*hul 12

int a[3] = {1,2,3};
int (*p)[3];
p=&a;    
printf("%d %d %d",(*p)[0],(*p)[1],(*p)[2]); 
Run Code Online (Sandbox Code Playgroud)

首先,您必须了解a和&a之间的区别.Value两者的和&A将是相同的.但它们的含义存在巨大差异.这里a代表first element一个arrayie &a[0]&a代表整体或complete array.如果你这样做a+1,你会发现下一个元素的地址array,即&a[1],但如果执行&a+1,它会给next addresscomplete array这里,即&a+1= &a[2]+1.因此,这里p=&a意味着您已分配address of an arraysize 3一个pointer p.


Tho*_*sin 5

示例*p[3]:

int a = 10;
&a; // <-- this is the address of the variable a
int b = 20;
int c = 30;
int *p[3];  // <-- array of three pointers
        // p[0] being the first, p[2] being the last and third
        // p is the address of p[0]
p[0] = &a;
p[1] = &b;  // Stored the addresses of a, b and c
p[2] = &c;

p[0];   // pointer to a

*p[0];  // this is the variable a, it has the value 10
Run Code Online (Sandbox Code Playgroud)

示例(*p)[3]:

int a[3];   // array of three integers
a[0] = 10;
a[1] = 20;
a[2] = 30;
a;      // address of the very first element, value of which is 10
&a;     // address of the pointer, the address holding variable

int (*p)[3];    // pointer to an array of three integers
p = &a;

// p is a variable
// p points to a
// a is a variable
// a points to a[0], 10
// a, therefore, is a pointer
// p points to a pointer
// p, therefore, is a pointer to a pointer
Run Code Online (Sandbox Code Playgroud)

写这一切真是有趣,有点儿.我希望它也有助于更好地理解.