繁体   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