我很好奇为什么在这段代码中 *(ptr + 1) 的值在程序运行时变成 1 而不是 6。
#include <stdio.h>
int main (void)
{
int *ptr, content = 3;
ptr = &content;
*(ptr + 1) = 6;
*(ptr + 2) = 10;
*(ptr + 3) = 14;
int i = 0;
for (i = 0; i < 4; ++i)
{
printf("The address is %p and the content is %d \n", ptr+i, *(ptr+i));
}
return 0;
}
当run int 6修改为1的值。
*(ptr + 1) = 6;
这是程序的输出:
The address is 0x7fff7b400a88 and the content is 3
The address is 0x7fff7b400a8c and the content is 1
The address is 0x7fff7b400a90 and the content is 10
The address is 0x7fff7b400a94 and the content is 14
我在 valgrind 中运行它,没有出现错误或任何错误,也尝试用谷歌搜索它,也许我在搜索错误的东西,但没有找到结果。
最佳答案
您正在修改未分配给您的内存,因此这是未定义的行为。
可能发生的是变量i
被分配到那个位置因为它是下一次使用堆栈空间 在函数中。 i
在那个时候是 1。所以输出是1。
改变
int content = 3;
ptr = &content;
到
int content[10] = {3};
ptr = &content[0]; //or ptr = content; but this may be harder to grasp if you are new to C
(感谢@KeithThompson 修复了指针赋值)
如果您只是想尝试指针运算。这将起作用,因为现在您拥有 10 个 int
s
关于c - 为什么指针值被修改为值 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14132376/