Reputation: 585
I'm working on a programming assignment and having some trouble with my pointers. The code sample below isn't from my homework, but is illustrative of the problems I'm having. I'm trying to pass the pointer to an object to another function (from change to really) and have that function create a new object and then return it. But, I'm finding that the original object isn't really changed. I can't figure out why not, as I'm using malloc to allocate it on the heap, and so the object should persist beyond the function creating it.
In the code sample below, I'm looking for the output:
a = 3
a = 5
But instead I'm getting
a = 3
a = 3
Even just some pointers in the right direction would be useful! Thank you!
Sam
Notes
Sample Code
#include <stdio.h>
#include <stdlib.h>
void really(int *a) {
/* Allocate pointer to new int, set it to 5, and
then set the pointer passed in equal to the new pointer */
int *b = malloc(sizeof(int));
*b = 5;
a = b;
}
void change(int *a) {
/* We don't actually change the object in this function;
we are instead passing it to a different function to change */
really(a);
}
int main() {
int a = 3;
printf("a = %d\n", a);
change(&a);
printf("a = %d\n", a);
return 0;
}
Upvotes: 1
Views: 796
Reputation: 11453
C only supports pass by value
. When you pass pointers to a function, the value of the pointer (ie. the address it points to) is copied to the function-parameter, a new variable.
In your function really()
, you have overwritten the address stored by the new pointer a
by the address pointed to by b
. So, that would not reflect in main()
. But if you had dereferenced a
and assigned it the new value 5
, the value of a
in main()
would also change.
Upvotes: 6
Reputation: 50657
You should change its value, not its pointer.
Change (in really()
)
a = b; // after this, a and b will both pointer to b's value
to
*a = *b; // change *a's value equal to *b's value
Upvotes: 1