2016-03-24 43 views
0
#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; 
} 

我期望的*pprintf()要的無論是在0x7ffc000f47c8的值,而不是指針的無符號值的值p(956816552))Deferencing指針與增量(* P ++ = x)的變化* P的至p

何時/如何將*p的值設置爲956816552(值爲p)?我認爲*p++ = 4不是UB。 (根據第一個回答的評論 - Undefined behavior and sequence points

任何幫助將不勝感激。謝謝。

+3

*我相信* p ++ = 4不是UB *可能不是,但是在解除引用p之後,它現在指向您並不真正擁有的內存 – stijn

+0

C++行爲準則:只有在您知道所有者時才解除引用。 – CinCout

+0

可能'p'恰好在內存中跟隨'i',所以'p ++'離開'p'指向自己。你確實看到「無論在0x7ffc000f47c8」 –

回答

3

執行增量p++之後,p不能再取消引用,因爲它不再指向對象。該程序調用未定義的行爲來取消引用p,此時我們通常會說「程序錯誤」,修復程序,然後繼續。

如果您對打印的確切值感到好奇,該值可能僅僅是偶然發生的事故,或者可能是其他情況。

注意:在這種情況下,增量本身是明確的。但是如果你再次增加指針,你會遇到麻煩,因爲你已經移動到了i的末尾。

1

更改程序通過以下方式

#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被shanged。

語句後

*(p++)=4; 

指針p被改變,而現在的點超出變量x所以,你可能不取消引用指針。

相關問題