int x=10;
int *y=&x;
int *z= &y;
printf("%d\n",*(*z));
我想明白为什么我们需要int **z
?这里有什么问题?
最佳答案
这是一个方便的表格,显示了基于您的声明的各种表达式的类型:
Expression Type Value
---------- ---- -----
x int 10
&x int * address of x
y int * address of x
&y int ** address of y
因为expression&y
的类型是int **
,所以需要声明z
为int **
来保存该值(因此表达式 &z
的类型将是 int ***
)。
那么,为什么它很重要?指针就是指针就是指针,对吧?
嗯,不一定。指向不同类型的指针可能具有不同的大小和表示形式。来自online 2011 standard :
6.2.5 Types
...
28 A pointer tovoid
shall have the same representation and alignment requirements as a pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.
48) The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.
在桌面和服务器世界中,大多数架构都是这样的,所有指针类型都具有相同的大小和表示形式,但有很多古怪的架构并非如此。您可以拥有一个词寻址架构,其中多个 char
值被打包到一个词中; char *
需要有几个额外的位来索引该词以获得特定的 char
值。您可以拥有哈佛架构,其中数据的地址行比代码的地址行少(反之亦然),因此指向对象类型的指针和指向函数类型的指针将具有不同的大小。
这里还有另一个问题:指针运算。由于 y
指向类型为 int
的对象,因此表达式 y++
将使 y
指向下一个对象int
类型。由于 z
指向一个类型为 int *
的对象,表达式 z++
将推进 z
指向下一个int *
类型的对象。如果 int
和 int *
的大小不同,则 y
和 z
将提前不同的数量。
简而言之,输入很重要,即使是指针。
关于c - 我想了解为什么我们需要 `int **z` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16966562/