I was studying for a test with the following question with the given output :
#include <stdio.h>
int main()
{
int i = 10;
int *const p = &i;
foo(&p);
printf("%d\n", *p);
}
void foo(int **p)
{
int j = 11;
*p = &j;
printf("%d\n", **p);
}
Output : 11 11
I understand that the address of *p
pointing to int i
is passed to the function foo
. Here, **p
is a pointer pointing to *p
, where *p
points to int i
.
In the function, **p
pointer changes and points to int j
, and the first printf
is called and 11 is printed.
What I don't understand is the output from the 2nd printf
function. Why is it printing 11, when it should be 10? I've checked and the value of int i
and it did not change, so shouldn't dereferencing *p
give 10 and not 11.
Can someone explain to me the logic behind what is happening and why is it happening?
CodePudding user response:
First you asign p the address of i and you input the address of p to the function foo and inside the foo function the the value of p becomes what every the value in j (*p = &j). When the memory address changes in the foo function you are not changing it back.
NOTE: There the variable p is not passed by value, It is passed to the function by reference. So any change you do to the p variable inside the foo function will affect the p variable inside the main function because they have the same memory address
CodePudding user response:
The line:
*p = &j;
makes the original variable
int *const p
point to the address of the local variable
int j
After foo is called, that local variable j has since been deallocated from the stack, but p is still pointing to that same stack location which still has that value of 11. So you are illegally accessing deallocated stack memory but it just happens to remain the value of 11. So it is printed a second time.
CodePudding user response:
I've tried this code :
#include<stdio.h> #include<stdlib.h> void foo(int *p) { int j = 11; p = &j; printf("%d\n", *p); } int main() { int i = 10; int *p = &i; foo(&p); printf("%d\n", *p); }