Reputation: 609
Here's what I've coded:
#include <stdio.h>
void add(int *a, int i){
while(i != 0){
a++;
i--;
}
}
int main(){
int a = 6;
add(&a, 4);
printf("a = %d\n", a);
return 0;
}
And here's the result
a = 6
The result I'm expecting is 10
, of course, but I don't understand why a
isn't modified when I pass it as a pointer in my add
function...
Upvotes: 1
Views: 821
Reputation: 29
AntonH's comment above is the right answer.
I'll expand it:
void add(int *a, int i){
while(i != 0){
a++;
i--;
}
}
You have defined 'a' as a pointer to an int (int*). Anything you do on 'a' such as '++'ing it is done on the pointer, not on the pointed value.
You should, therefore, replace a++
with (*a)++
to increase "what is pointed by a"
Upvotes: 2
Reputation: 1903
You function should be like this
void add(int *a, int i){
while(i != 0){
(*a)++; // deference the value and increment it.
i--;
}
}
with this
/* move the pointer to the next location */
a++;
Upvotes: 2
Reputation: 311068
In the function there is advanced the pointer itself instead of incrementing the value pointed to by the pointer. Change the function the following way
void add(int *a, int i){
while(i != 0){
( *a )++;
i--;
}
}
Or the expression statement ( *a )++;
can be substituted for ++*a;
Also the function could be more safe if the second parameter had type unsigned int
. Otherwise you have to check the sign of the parameter.
Upvotes: 4