Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a pointer cast as (void*)p when used in printf? [duplicate]

Tags:

c

char  x = 'G';
char *p = &x;

printf ("Address of x: %p\n", p);
printf ("Address of x: %p\n", (void*)p);

Can someone tell me what exactly (void*)p means? I know that it is the same as p, as that also gives me the address of x, but why is this written as (void*)p?

like image 728
Kai Avatar asked Feb 08 '19 18:02

Kai


1 Answers

The C standard says this about the %p format specifier for printf family functions (§ 7.21.6.2, paragraph 12)

The corresponding argument shall be a pointer to a pointer to void.

Pointers to different types may differ in their internal representation, except for void * and char * pointers, which are guaranteed to be the same size. However, any object pointer type is convertible to void *. So, to be sure that all %p variables are processed correctly by printf, they are required to be void *.

like image 109
Govind Parmar Avatar answered Oct 21 '22 01:10

Govind Parmar