简体   繁体   English

C-递增和递减指针,然后获取值

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

The following code outputs y as a massive integer, not 15 . 以下代码将y输出为整数而不是15 I don't understand why. 我不明白为什么。 I know the -- and ++ operators come before the * operator, so it should work. 我知道--++运算符位于*运算符之前,因此它应该可以工作。

What the follwing code is trying to say. 以下代码试图说什么。

/*
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;
}

If instead, I change the code to the following: 如果相反,我将代码更改为以下内容:

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

    return 0;
}

That code outputs 15 . 该代码输出15 Why? 为什么?

The difference is between x++ and ++x , post- and pre-increment of a pointer. x++++x之间的区别是指针的后递增和前递增。

  • When ++ is after x , the old value is used prior to the increment 如果++x之后,则在增量之前使用旧值
  • When ++ is before x , the new value is used after the increment. 如果++x之前,则在增量之后使用新值。

This will work: 这将起作用:

int y = *(--test);

Although parentheses are not necessary, it is a good idea to use them for clarity. 尽管括号不是必需的,但为清楚起见,最好使用括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM