CBFalconer said:
Nikhil said:
Thanks for pointing out my mistakes. This is my edited program:
#include <stdio.h>
int main() {
int a[3][3][3];
printf("%p %p %p %p",a,*a,**a,&a);
return 0;
}
Its still printing the same value for all of them. How does it
happen??
Because you are still lying to printf and getting undefined
behaviour. %p requires a void* parameter. I also fixed your
#include statement.
It's true that the above program lies to printf and thereby invokes
undefined behavior. It's also true that one possible consequence of
this undefined behavior is to print the same value four times.
But it's almost certainly *not* true that the program prints the same
value four times *because* it invokes undefined behavior.
In most implementations, the behavior of passing a pointer value of a
type other than void* to printf with a "%p" is exactly the same as the
behavior of passing the same pointer value converted to void*. That's
not guaranteed by the standard, of course, but it's very common. In
the above program with that correction (casting all printf arguments
after the format string to void* -- oh, yes, and adding a trailing
"\n"), I would still expect it to print the same value four times.
I'm not sure whether it's even possible for a conforming
implementation *not* to print the same value four times.
Yes, the program exhibits undefined behavior, and yes, that absolutely
should be fixed, but that doesn't actually explain the behavior, and
there is another explanation. There's nothing wrong with pointing out
the undefined behavior *and then* answering the original question.
In other words, why does *this* program print the same value four
times? (I changed the spaces to new-lines to make it easier to see
that all for values are the same.)
#include <stdio.h>
int main(void)
{
int a[3][3][3];
printf("%p\n%p\n%p\n%p\n", (void*)a, (void*)*a, (void*)**a, (void*)&a);
return 0;
}
(My answer to that is "Read section 6 of the comp.lang.c FAQ".)