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.