Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using %x to print the hex address contained in a pointer

i just read this short article http://karwin.blogspot.com/2012/11/c-pointers-explained-really.html which describes pointers really well. The author however says that the addresses are just these hex values, so he prints it with %x, but when i do this not only do i get a warning from the compiler saying i am passing a pointer instead of an unsigned int, but sometimes i get something that doesn't resemble an address at all (like 1C). Can somebody clarify the issue please?

like image 687
user96454 Avatar asked Sep 06 '25 09:09

user96454


1 Answers

%x expects its corresponding argument to have type unsigned int, which is why you get the warning and funky output. Use %p to display pointer values:

T *p = some_pointer_value;
...
printf( "p = %p\n", (void *) p );

%p expects its corresponding argument to have type void *. This is pretty much the only place you should explicitly cast a pointer to void * in C.

Edit

Just looked at the page. Be aware, that code sample is old (written ca. 1990) and uses K&R-style (pre-1989 standard) function definition syntax and implicit int all over the place. It's using %x to display pointer values because the %p conversion specifier wasn't added to the language until the 1989 standard.

It should not be used as a model of modern C programming practice.

His explanation of pointers is pretty decent, though.

like image 138
John Bode Avatar answered Sep 09 '25 02:09

John Bode