I am learning pointers in C, and am trying to solve exercises on pointers available online. Although the below question doesn't make use of pointers, I understand that the incorrect output is due to lack of usage of pointers. Here is the question-
/* p2.c
Find out (add code to print out) the address of the variable x in foo1, and the
variable y in foo2. What do you notice? Can you explain this?
*/
And here is my answer-
#include <stdio.h>
void foo1(int xval)
{
int x;
x = xval;
/* print the address and value of x here */
printf("\n Address of variable x is:%p\n", &x);
printf("\n Value of variable x is: %d\n", x);
}
void foo2(int dummy)
{
int y;
y=dummy;
/* print the address and value of y here */
printf("\n Address of variable y is:%p\n", &y);
printf("\n Value of variable y is: %d\n", y);
}
int main()
{
foo1(7);
foo2(11);
return 0;
}
The output when compiling the program is-
Address of variable x is:0x7fff558fcb98
Value of variable x is: 7
Address of variable y is:0x7fff558fcb98
Value of variable y is: 11
From what I understand, when the program runs, and foo1
with an integer as function argument is called, the integer 7
is taken and stored in the integer variable x
. The function foo1
then prints the address and value of variable x
. Same thing repeats with function foo2
.
But, I couldn't understand how is it that two integer variables with different values are residing at the same memory address 0x7fff558fcb98
? Is it because of memory management issues in C (malloc
, free
etc-I'm not there yet!)?
Any help would be highly appreciated. Thank You.
It's useful to visualize the state of the stack to understand the behavior. When you are in main, let's say the stack looks like:
When you enter foo1
, the stack frame for foo1
is added to the stack and it looks like:
When you return from foo1
, the stack will revert to:
When you enter foo2
, the stack frame for foo2
is added to the stack and it looks like:
The state of the stack frame looks very similar for foo1
and foo2
. It's not surprising that the addresses of the local variables x
and y
are identical.
Had the number of arguments, the arguments types or the local variable types been different, you would have noticed different values for the addresses of the local variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With