I need to analyze the output of the following program:
#include "stdio.h"
void foo(int **const p)
{
int j = 11;
*p = &j;
printf("%d ", **p);
}
int main()
{
int i = 10;
int *p = &i;
foo(&p);
printf("%d ", *p);
printf("%d ", *p);
}
I know nobody actually writes this way, but nonetheless. I expected it to output something like 11 [garbage] [garbage]
, only to find the answer is 11 11 [undefined value]
. I decided to spin a bit.
#include "stdio.h"
void foo(int **p)
{
int j = 11;
*p = &j;
printf("1:-");
printf("%d-", **p);
}
int main()
{
int i = 10;
int *p = &i;
foo(&p);
/* printf("2:-"); */
printf("%d-", *p);
printf("3:-");
printf("%d-", *p);
}
This would give 1:-11-11-3:-0-
on my platform (macOS 10.12.2, tested both on Apple LLVM version 8.0.0 (clang-800.0.42.1) and Homebrew gcc 6.2.0).
And if I un-comment that printf("2:-");
line I would get 1:-11-2:-0-3:-0-
. The second call prints p
differently. Again both compilers yield same result.
Here are my questions:
Is the original answer even correct? And how is it (in)correct?
Why and how does that commented call to
printf
changes the content ofp
? Or am I missing the point?