%p format specifier needs explicit cast to void* for all types but char* in printf

  • A+

I've read a lot of answers about the %p format specifier usage in C language here in Stack Overflow, but none seems to give an explanation as to why explicit cast to void* is needed for all types but char*.
I'm of course aware about the fact that this requirement to cast to or from void* is tied with the use of variadic functions (see first comment of this answer) while non-mandatory otherwise.

Here's an example :

int i;     printf ("%p", &i); 

Yields a warning about type incompatibility and that &i shall be casted to void* (as required by the standard, see again here).

Whereas this chunk of code compiles smoothly with no complaint about type casting whatsoever:

char * m = "Hello";     printf ("%p", m); 

How does that come that char* is "relieved" from this imperative?

PS: It's maybe worth adding that I work on x86_64 architecture, as pointer type size depends on it, and using gcc as compiler on linux with -W -Wall -std=c11 -pedantic compiling options.


There is no explicit cast needed for arguments of type char*, as char * has the same representation and alignment requirement as void *.

Quoting C11, chapter §6.2.5

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. (48) [...]

and the footnote 48)

The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: