Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 897
reuta Avatar asked Feb 27 '26 16:02

reuta


1 Answers

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.

like image 62
R Sahu Avatar answered Mar 02 '26 04:03

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!