簡體   English   中英

C-遞增和遞減指針,然后獲取值

[英]C - Increment and decrement pointer, then retrieve value

以下代碼將y輸出為整數而不是15 我不明白為什么。 我知道--++運算符位於*運算符之前,因此它應該可以工作。

以下代碼試圖說什么。

/*
Create a variable, set to 15.
Create a pointer to that variable.
Increment the pointer, into undefined memory space.
Decrement the pointer back where it was,
then return the value of what is there,
and save it into the  variable y.
Print y.    
*/

int main()
{
    int x = 15;
    int *test = &x;
    test++;
    int y = *test--;
    printf("%d\n", y);

    return 0;
}

如果相反,我將代碼更改為以下內容:

int main()
{
    int x = 15;
    int *test = &x;
    test++;
    test--;
    printf("%d\n", *test);

    return 0;
}

該代碼輸出15 為什么?

x++++x之間的區別是指針的后遞增和前遞增。

  • 如果++x之后,則在增量之前使用舊值
  • 如果++x之前,則在增量之后使用新值。

這將起作用:

int y = *(--test);

盡管括號不是必需的,但為清楚起見,最好使用括號。

暫無
暫無

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

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