2016-03-11 220 views
-6

我最近一直在研究中的指針C,和我不能似乎完全理解此代碼:差異,* PTR和&PTR

int *ptr= (*int) 99999; 
*ptr = 10; 
printf("%d\n,*ptr); //Outputs: 10 
printf("%p\n",&ptr); //Outputs: 0029FF14 
printf("%p\n",ptr); //Outputs: 0001869F 

問題?

  1. 是「& ptr = 0029FF14」存儲「* ptr = 10」的存儲位置嗎?
  2. 「ptr = 0001869F」是否存儲「& ptr = 0029FF14」的存儲位置?如果不是那麼ptr是什麼?

謝謝!

我相信這個問題不同於「C指針語法」後,因爲它不區分ptr,* ptr和& ptr,這意味着帖子並沒有解釋爲什麼「ptr」包含不同的值,具體取決於它隨附的操作員。 [EDITED]

+3

你爲什麼認爲選擇一個隨機存儲位置可以工作? aka這行''ptr = 10;' –

+1

該代碼不會提供那些輸出,實際上不會編譯。 – OrangeDog

+0

@EdHeal這行不是問題。 'int * ptr =(* int)99999;'is。 – glglgl

回答

2
  • ptr是指針本身。
  • *ptr是它指向的值。
  • &ptr是指針的地址。

所以IOW,

  1. &a是其中a被存儲的存儲器位置。

  2. a是存儲*a的存儲位置。

2

讓我們修復的幾件事情:

int *ptr= (*int) 99999; 
*ptr = 10; 

永遠不要做,除非你知道你在做什麼(你是玩弄鏈鋸)

反而讓做一個真正的int和玩它。

int test_int = 10; 
int *ptr = &test_int; 
printf("%d\n",*ptr);  //Outputs: 10 
printf("%d\n",test_int); //Outputs: 10 too 
printf("%p\n",&ptr);  //Outputs: the location of ptr - its address 
printf("%p\n",ptr);  //Outputs: the location of test_int 
printf("%p\n",&test_int); //Outputs: the location of test_int too 
相關問題