取数组地址时的不同指针算法结果

mrg*_*mrg 50 c pointers language-lawyer

程序:

#include<stdio.h>

int main(void) {
    int x[4];
    printf("%p\n", x);
    printf("%p\n", x + 1);
    printf("%p\n", &x);
    printf("%p\n", &x + 1);
}
Run Code Online (Sandbox Code Playgroud)

输出:

$ ./a.out
0xbff93510
0xbff93514
0xbff93510
0xbff93520
$
Run Code Online (Sandbox Code Playgroud)

我希望以下是上述程序的输出.例如:

x        // 0x100
x+1      // 0x104  Because x is an integer array
&x       // 0x100  Address of array
&x+1     // 0x104
Run Code Online (Sandbox Code Playgroud)

但是最后一个陈述的输出与我预期的不同.&x也是数组的地址.因此,在此处递增1将打印地址递增4.但是&x+1地址递增10.为什么?

the*_*ace 64

x -> Points to the first element of the array.
&x ->Points to the entire array.
Run Code Online (Sandbox Code Playgroud)

偶然发现了一个描述性的解释:http://arjunsreedharan.org/post/69303442896/the-difference-between-arr-and-arr-how-to-find

SO链接:为什么arr和&arr一样?


i48*_*486 26

如果4你0x100 + sizeof xsizeof x4*sizeof int= 4*4 = 16 = 0x10的.

(在您的系统上,sizeof int是4).


小智 9

评估这个问题的简单方法是:

增量上的任何指针都指向其基类型的下一个内存位置.

这里&x的基类型是int(*p)[4],它是指向4个整数数组的指针.

因此,此类型的下一个指针将指向原始数组的16个字节(假设int为4个字节).