#include <stdio.h>
int main(){
int i=1;
int * p = &i;
*(p++)=4;
printf("%p\n", p); //0x7ffc000f47c8
printf("%u\n", p); //956816552 (which is 0x7ffc000f47c8 as unsigned integer)
printf("%u\n", *p); //956816552 (I would expect *p to be the value of whatever is in 0x7ffc000f47c8, and not the unsigned value of the pointer p (956816552))
return 0;
}我希望printf() of *p是0x7ffc000f47c8中的值,而不是指针p (956816552)的无符号值)。
何时/如何将*p的值设置为956816552 (p值)??
我相信*p++ = 4不是UB。(根据第一个答案-Undefined behavior and sequence points的评论)
任何帮助都将不胜感激。谢谢。
发布于 2016-03-24 11:42:29
执行增量p++后,不能再取消对p的引用,因为它不再指向对象。程序调用取消引用p的未定义行为,此时我们通常会说“程序错误”,修复程序,然后继续前进。
如果您对打印出来的确切值感到好奇,那么这个值可能只是&i+1碰巧指向的一个意外,或者可能是其他的东西。
注:在本例中,增量本身是定义良好的.但是,如果再次增加指针,就会遇到麻烦,因为您已经超过了i的末尾。
发布于 2016-03-24 11:55:49
按以下方式更改程序
#include <stdio.h>
int main(){
int i=1;
int * p = &i;
*(p++)=4;
printf("%p\n", p); //0x7ffc000f47c8
printf("%u\n", p); //956816552 (which is 0x7ffc000f47c8 as unsigned integer)
printf("%d\n", i); //956816552 (I would expect *p to be the value of whatever
^^^^^^^^^
is in 0x7ffc000f47c8, and not the unsigned value of the pointer p (956816552))
return 0;
}你会看到i被人吓了一跳。
事后陈述
*(p++)=4;指针p被更改,现在指向变量x之外,所以您可能不会取消对指针的引用。
https://stackoverflow.com/questions/36199297
复制相似问题