Reputation:
While studying C language for university I ran into some uncertainties about pointers, so I wrote the most simple code I could think about it.
void test1(int *int_pointer) {
*int_pointer = 5;
}
void test2(int *int_pointer) {
int i = 6;
int_pointer = &i;
}
int main(void) {
int n = 8;
int *p = &n;
test1(p);
test2(p);
}
Why if I printf("%i", * int_pointer)
into test2 function it prints out 6 while printf("%i", * p)
in main comes out 5 (and not 6)?
The second question is about the following code.
int main (void) {
int var1 = 10;
int * var1p = & var1;
int var2 = * var1p / 2;
int * var2p = &var2;
var1 = 40;
printf("%i", * var2p);
}
Why in this case comes out 5 and not 20 if I change var1 value and var2p points to var2 (which is equals to * var1p / 2)?
Thanks in advance.
Upvotes: 1
Views: 83
Reputation: 51
In the first case:
You initialize a variable n
and you make a p
pointer to point at
it.
Then you give the value of the p
(the address of n
) to test1()
and change the value of the memory field that is pointed by
int_pointer
(and int_pointer
has the same value as p
, so it
changes the value of n
.
When you call test2()
and give you the same address, but in the
function you change the value of the local int_pointer
, so it will
point to the local i
, but the p
stays the same.
So that is why in the test2()
function 6 is printed (the value that
is pointed by int_pointer
), and in the main()
5 is printed (the
value that is pointed by p
).
The second case:
You initialize var1
to 10, and then you make var1p
to point at
it.
Then you initialize var2
to half, what is pointed by var1p
, so
10/2=5.
Then you initialize var2p
, so it will point to var2
.
After that, you change the value of var1
but var2
stays the same,
so that is why you getting 5.
var1
and var2
is two different variable, so they have their own
fields in memory. If you want 40 to be printed you should make
var2p
to point at var1
, like var2p = &var1
.
Upvotes: 2
Reputation: 386386
test1
modifies the variable pointed by int_pointer
(main
's n
).
test2
modifies the pointer itself. Argument variables are local to the function to which they belong, and changing them has no effect on the caller.
For example, the following has no effect on the caller either:
void test3(int i) {
i = 9;
}
test(n);
If you wanted to modify a pointer in the caller, you'd have to pass a pointer to the pointer.
void test4(int **int_pointer_pointer) {
int *int_pointer = malloc(sizeof(int));
*int_pointer = 10;
*int_pointer_pointer = int_pointer;
}
int *int_pointer;
test4(&int_pointer);
printf("%d\n", *int_pointer);
free(int_pointer);
Note that returning (normally or via arguments) a pointer to a local variable makes no sense because it ceases to exists when the function returns. That's why I used malloc
+free
instead of a local variable.
Upvotes: 1