I have the following code in which I wrote two functions. Both are meant to produce the same output. But the function g()
which has loop produces a different output from what I had expected as shown below.
#include <stdio.h>
struct S { int i; };
void f(void)
{
struct S *p;
int i = 0;
p = &((struct S) {i});
printf("%p\n", p);
i++;
p = &((struct S) {i});
printf("%p\n", p);
}
void g(void)
{
struct S *p;
for (int i = 0; i < 2; i++)
{
p = &((struct S) {i});
printf("%p\n", p);
}
}
int main()
{
printf("Calling function f()\n");
f();
printf("\nCalling function g()\n");
g();
}
Output:
Calling function f()
0023ff20
0023ff24
Calling function g()
0023ff24
0023ff24
How come the address of p
is same in case of g()
when it was called?