c - Increment content of pointer -


i trying increment value in c , return old value, , doing using pointer. problem new value still 0 though using pointer.

#include <stdio.h> #include <stdlib.h>  int increment (int *mem) {     int tmp;     tmp = *mem;     *mem++;     return tmp; }  int main () {     int = 0;     printf("the old value of \t %d", increment(&a));     printf("the new value of \t %d", a); } 

now when run method same value 0; expecting 1 in second printf. don't know doing wrong here.

change this

*mem++; 

to this

(*mem)++; 

the problem lies in operators priority. may want read c operator precedence.


so, code do? increments value of pointer, since ++ operator activated first , * gets activated, having no real effect.

as result, code invokes undefined behavior, since access (and write) invalid memory location since pointer incremented before value written it.


Comments