c: when using a pointer as input in a function incrementing the pointers value by using *pointer++ doesn't work

我怕爱的太早我们不能终老 提交于 2019-12-14 03:49:56

问题


While I was learning C (I am very new to it), I was playing around with pointers. Here you can see my code:

#include <stdio.h>

void change(int *i)
{
    *i += 1;  
}

int main()
{   
    int num = 3;

    printf("%d\n", num);
    change(&num);
    printf("%d\n", num);

    return 0;
}

My aim was to replace incrementing the num value without reassigning it like so:

num = change(num);

That's why I was passing the memory location of num using the &: so it could be used as a pointer. Before this version everything in the code was the same. The only thing that was different was that I said *i++; instead of saying *i += 1;

Now my question is why can't I say *i++?


回答1:


Now my question is why i can't say *i++

Due to operator precedence, *i++ is same as *(i++).

*(i++);

is equivalent to:

int* temp = i;  // Store the old pointer in a temporary variable.
i++;            // Increment the pointer
*temp;          // Dereference the old pointer value, effectively a noop.

That is not what you want. You need to use (*i)++ or ++(*i). These will dereference the pointer first and then increment the value of the object the pointer points to.




回答2:


This is due to operator precedence.

You can see that "postfix increment" is at precedence level 1, and "Indirection (dereference)" at level 2, and level 1 happens first. So you need to use brackets to get the dereference to happen first: (*i)++.

The difference is (*i)++ says locate the memory pointed to by i, and increment it (which you want). *(i++) says increment i itself (so it points to the next memory address), and dereference that; which is possibly a no-op, and not what you want.



来源:https://stackoverflow.com/questions/38511061/c-when-using-a-pointer-as-input-in-a-function-incrementing-the-pointers-value-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!