Reputation: 2319
I am trying to increment a value in C and return the old value, and I am doing that using a pointer. The problem is that the new value is still 0 even though I am using pointer.
#include <stdio.h>
#include <stdlib.h>
int increment (int *mem) {
int tmp;
tmp = *mem;
*mem++;
return tmp;
}
int main () {
int a = 0;
printf("The old value of a is \t %d", increment(&a));
printf("The new value of a is \t %d", a);
}
Now when I run this method I get the same value for a that is 0; I was expecting 1 in the second printf. I don't know what I am doing wrong here.
Upvotes: 1
Views: 1291
Reputation: 393
In addition to what everyone else has posted about operator precedence, if you are passing in a pointer to an int to be incremented there is no reason to return a copy of the int via tmp
. You will have access to the value in mem
outside of the function.
#include <stdio.h>
#include <stdlib.h>
void increment (int *mem) {
(*mem)++;
}
int main () {
int a = 0;
printf("The old value of a is \t %d", a);
increment(&a);
printf("The new value of a is \t %d", a);
}
Upvotes: 0
Reputation: 73424
Change this
*mem++;
to this
(*mem)++;
The problem lies in the operators priority. You may want to read about C Operator precedence.
So, what does your code do? It increments the value of the pointer, since ++
operator is activated first and then *
gets activated, having no real effect.
As a result, your code invokes undefined behavior, since you access (and eventually write) into an invalid memory location since the pointer is incremented before the value is written to it.
Upvotes: 9
Reputation: 809
Maybe you missed some parentheses?
#include <stdio.h>
#include <stdlib.h>
int increment (int *mem) {
int tmp;
tmp = *mem;
(*mem)++; // problem was here.
return tmp;
}
int main (){
int a = 0;
printf("The old value of a is \t %d", increment(&a));
printf("The new value of a is \t %d", a);
}
Upvotes: 5