簡體   English   中英

無法理解這個簡單的代碼輸出

[英]Can't Understand this simple code output

碼:

int a = 5;
int *ptr;
ptr = &a;

printf("%d",*ptr);
printf("\n%d",*(ptr++));
printf("\n%d",(*ptr)++);
printf("\n%d",++(*ptr));

輸出:

5
5
1638268
1638268

我期待輸出為:5垃圾5 7 Sory,我的指針和運算符優先級概念非常暗淡。 無法理解這個簡單的輸出。

  1. 第一個顯然是5,只是解除引用指針
  2. 還有五個因為后綴運算符返回指針preincrement
  3. 3和4是垃圾,因為指針不再指向已分配的內存

如果您希望第二個按照預期行事並打印垃圾,則可以使用前綴++代替

int a = 5;
int *ptr;
ptr = &a;

printf("%d",*ptr);          // 5 as you expected.
printf("\n%d",*(ptr++));    // 5, because the pointer is incremented after this line
printf("\n%d",(*ptr)++);    // Not 5 because pointer points to another location.
printf("\n%d",++(*ptr));    // Pointer already changed, no longer pointing at 5.
int a = 5;
int *ptr; 
ptr = &a;  // ptr is the address of the int 5

printf("%d",*ptr);  // dereferences ptr, which points to in 5
printf("\n%d",*(ptr++));  // increments ptr by one, so ptr not points to 
                          // an int one over from wherever int 5 is in memory
                          // but return ptr before incrementing and then dereference it
                          // giving int 5
printf("\n%d",(*ptr)++);  // dereference ptr, which is now one int over from 5 thanks
                          // to the last line, which is garbage, try 
                          // to increment garbage by 1 after printing
printf("\n%d",++(*ptr));  // dereference ptr, which is now one int over from 5, 
                          // try to increment garbage by one before printing

*ptr只是給在這不過是價值的位置值a

*(ptr++)相當於(*ptr)然后(ptr += 1)因為增量,所以首先它給出了printf使用的值,然后遞增指針,所以它現在指向垃圾內存。

(*ptr)++相當於(*ptr)然后(*ptr += 1) ,所以它取值垃圾內存並遞增它。

++(*ptr)相當於(*ptr) += 1所以它會增加垃圾位置的值,現在你可以看到undefined behavior的效果,所以你沒有得到最后一個遞增的值加一,但得到了由於未定義的行為,與最后一個值相同。 在我的編譯器上,我得到了最后一個遞增的值加一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM