Possible Duplicate:
Correct format specifier to print pointer (address)?
When printing a pointer using printf, is it necessary to cast the pointer to void *? In other words, in code like
#include <stdio.h>
int main() {
int a;
printf("address of a = %p\n", &a);
}
should the argument really be (void *) &a? gcc doesn’t seem to give any warnings when no explicit cast is made.
Yes, the cast to
void*is required.&ais of typeint*; printf’s"%p"format requires an argument of typevoid*. Theint*argument is not implicitly converted tovoid*, because the declaration ofprintfdoesn’t provide type information for parameters other than the first (the format string). All arguments after the format string have the default argument promotions applied to them; these promotions do not convertint*tovoid*.The likely result is that
printfsees an argument that’s really of typeint*and interprets it as if it were of typevoid*. This is type-punning, not conversion, and it has undefined behavior. It will likely happen to work ifint*andvoid*happen to have the same representation, but the language standard does not guarantee that, even by implication. And the type-punning I described is only one possible behavior; the standard says literally nothing about what can happen.(If you do the same thing with a non-variadic function with a visible prototype, so the compiler knows at the point of the call that the parameter is of type
void*, then it will generate code to do an implicitint*-to-void*conversion. That’s not the case here.)