首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不理解*p[3]和(*p)之间的区别[3]

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

Stack Overflow用户
提问于 2014-03-10 14:26:23
回答 8查看 3.8K关注 0票数 3

在我的书中,有人写到*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的例子。有人能给我举个例子吗?

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2014-03-10 14:28:56

代码语言:javascript
复制
int a[3] = {1,2,3};
int (*p)[3];
p=&a;    
printf("%d %d %d",(*p)[0],(*p)[1],(*p)[2]); 

首先,您必须理解a和&a之间的区别。Value of a和&a将是相同的。但它们的含义有很大的不同。这里,a表示first element of a array,即&a[0]&a表示整体或complete array。如果执行a+1,您将在array (即&a[1] )中找到下一个元素的next address地址,但如果执行&a+1,则会将next address分配给complete array,即这里的&a+1 = &a[2]+1。因此,这里的p=&a意味着您已经将address of an array of size 3分配给了pointer p

票数 13
EN

Stack Overflow用户

发布于 2014-03-10 14:40:44

*p[3]示例

代码语言:javascript
复制
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

(*p)[3]示例

代码语言:javascript
复制
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

写这些都挺有趣的。我希望这也有助于更好地理解。

票数 5
EN

Stack Overflow用户

发布于 2014-03-10 14:29:04

像这样吗?

代码语言:javascript
复制
int a[3]; // int array of size 3
int (*p)[3]; // pointer to int array of size 3

p = &a; // Make p point to the address of a

a是一个array of size 3,它可以包含三个元素。p被声明为pointer,它将指向int array of size 3

代码语言:javascript
复制
int a;
int *p;

a是一个整数。p是一个指向一个整数的指针,而不是一个整数数组,一个简单的整数。

简化:把指针看作一个变量,它的值只是其他变量的地址。您也可以指定指针可能指向的变量类型,在这种情况下,可以指定大小为3的int数组。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22302890

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档