I'm learning the fundamentals of C and I'm confused about the printf format specifiers %p and %x. They can both appear to print an address in hexadecimal, so what is the practical difference between them? When should each one be used, and why does it matter?
3 Answers
Although a pointer is represented like a number at the machine level, C does not treat pointers and integers as the same type. On many common computers, %x may appear to work for an address, but that is only accidental and is not portable C. The correct approach is %p for a pointer and %x for an integer value that you intentionally want shown in hexadecimal.
In an expression like printf("%pn", (void*)&x), the & operator obtains the address of x, and %p formats that pointer for display. Printing an address is mostly useful for learning, debugging, or inspecting how pointers work; ordinary programs usually don’t need to display addresses directly.
%p tells printf that the argument is a pointer, while %x tells it to expect an unsigned integer and display that integer in hexadecimal. Even if they produce similar-looking output on many systems, they are not interchangeable. Use %p for pointers, typically by casting the pointer to void*, such as printf("%pn", (void*)&x). Use %x when you actually want to print an integer in hexadecimal. Because printf is variadic, it relies on the format string to interpret each argument correctly, and using the wrong specifier can cause undefined behavior or fail on systems where integers and pointers have different representations.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically