C - 递增和递减指针,然后检索值

时间:2016-09-17 01:46:52

标签: c pointers

以下代码将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。为什么呢?

1 个答案:

答案 0 :(得分:5)

区别在x++++x之间,指针的后增量和预增量。

  • ++x之后时,旧值会在增量之前使用
  • ++x之前时,会在增量后使用新值。

这将有效:

int y = *(--test);

虽然没有必要使用括号,但为了清楚起见,最好使用括号。