c - 为什么指针值被修改为值 1?

标签 c pointers

我很好奇为什么在这段代码中 *(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 个 ints

数组中的整个堆栈空间

关于c - 为什么指针值被修改为值 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14132376/

相关文章:

c 打印指针指向的数组的地址

c - 使用相同的左值多次调用 strdup()

c - 不再有令人困惑的指针

c - 另一个C指针问题

c - 在 C 中为动态数字输入读取字符串时出现问题

c - 为什么 gcc 反汇编程序为局部变量分配额外的空间?

c - 如何读取 C 中函数参数的字符串?

c - 如何在给定程序中打印评论?

c - int数组排序修改数组内容

c++ - 对于 NULL 指针,我应该使用 NULL 还是 0?