C中的奇怪指针行为

Mad*_*ter 2 c pointers

我正在试验指针.看看这段代码:

#include <stdio.h>

int main() {

int numba = 1;

int *otherintptr = &numba;

printf("%d\n", otherintptr); 
printf("%d\n", *otherintptr);

*otherintptr++;

printf("%d\n", otherintptr);
printf("%d\n", *otherintptr);

return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

2358852 
1
2358856 
2358856 
Run Code Online (Sandbox Code Playgroud)

现在,我很清楚(*otherintptr)++会增加我的int,但我的问题不是这个.

增量后,内存位置正确增加4个字节,这是一个整数的大小.

我想知道为什么最后一个printf指令打印内存位置,而我明确要求打印标记为2358856的内存位置的内容(我当时期待一些脏的随机内容).注意,第二个语句按预期打印存储单元2358852的内容(整数).printf1

Cri*_*tik 6

这两条线会发生什么

int numba = 1;
int *otherintptr = &numba;
Run Code Online (Sandbox Code Playgroud)

由于C编译器将生成顺序存储器布局,otherintptr因此最初将指向与numba变量对应的存储器地址.这与调用时分配的堆栈帧有关main.

现在,堆栈上的下一个位置(实际上是前面的,如果我们认为堆栈在基于x86的架构上逐渐减少)被otherintptr变量占用.递增otherintptr会使它指向自身,因此您会看到相同的值.

举个例子,让我们假设堆栈main从内存中的0x20偏移量开始:

0x20: 0x1      #numba variable
0x24: 0x20     #otherintptr variable pointing to numa
Run Code Online (Sandbox Code Playgroud)

执行otherintptr++指令后,内存布局如下所示:

0x20: 0x1      #numba variable
0x24: 0x24     #otherintptr variable now pointing to itself
Run Code Online (Sandbox Code Playgroud)

这就是为什么第二个printf具有相同的输出.