简体   繁体   中英

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

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++ ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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