打印存储在指针中的内容会打印存储在该内存中的内容

时间:2018-01-06 20:57:16

标签: c

当我尝试打印时

#include <stdio.h>

int main(){
   int x = 3;
   int *ptr = &x;
   //printf("Address is : %d\n",&ptr);
   ptr++;
   *ptr = 1;
   printf("%d %d",x,ptr);
   return 0;
}

代码输出3 1,不应该是3(然后是ptr的地址?)。然后,当我取消注释第一个printf时,它打印出来:

地址是:6356744

3 6356752

有谁知道发生了什么事?

1 个答案:

答案 0 :(得分:1)

您的代码中存在几个严重问题。

1)使用%d打印指针值或变量地址但不应该。这是未定义的行为,因此我们无法知道会发生什么。要打印指针值或变量的地址,请使用%p并转换为void指针,如:

printf("Address is : %p\n",(void*)&ptr);

2)您写入未分配给您的程序的内存。这些行:

ptr++;
*ptr = 1;

让你写下值&#34; 1&#34;超过x一步。所以这也是未定义的行为。

更正以上内容可以为您提供此计划:

#include <stdio.h>

int main(){
   int x = 3;
   int *ptr = &x;
   printf("Address is : %p\n",(void*)&ptr);
   ptr++;
   // *ptr = 1;
   printf("%d %p\n",x,(void*)ptr);
   return 0;
}

可能的输出:

Address is : 0x7ffc5b0923c8
3 0x7ffc5b0923c8

但输出可能会从逐次运行和系统到系统

发生变化