Incremental pointer print garbage?

I wrote the following code:

void incrementNumber(int *num) { *num++; printf("%i\n", *num); } int main() { int i = 3; printf("%i\n", i); int *ptr = &i; incrementNumber(&i); printf("%i\n", i); getchar(); getchar(); return 0; } 

Whenever I output num as an increment number, it just prints the garbage, however, if I change the code to this:

 void incrementNumber(int *num) { *num += 1; printf("%i\n", *num); } 

It displays the values ​​as expected. I'm trying to get away from using references in order to better understand pointers, because (like most) my knowledge of pointers is quite limited, and so I'm trying to understand them better.

Also let me rephrase the question, I know why it displays this value for garbage, because it increments the memory address and prints garbage in this place, rather than increasing the value contained in the memory address, which I suppose I ask why it does it with a step, but not with an addition? Is this just how these two teams come down to assembly? Is there a way to increase the value indicated by the pointer in this way?

+6
source share
2 answers

This is due to priority: *num++ is evaluated as num++ and then dereferenced. When you print the next value, it means that in this case the pointer is invalid.

If you use (*num)++ , you will get the result you want.

+4
source

I am glad that you understand what is happening on this line:

 *num++; 

The problem is the priority of the operators. I believe that “++” takes precedence over “*” (in this context, of course). Try writing this, it will work the way you want:

 (*num)++; 

One thing that I did not know and just found out is that pointer operation in this context takes precedence over + =.

+4
source

All Articles