![](/img/trans.png)
[英]How can I increment or decrement pointer argument value in function call in C in one line?
[英]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.