What’s the difference between %p and %x when printing pointers in C?

0
4
Asked By MellowPine42 On

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

Answered By NorthStarLime5 On

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.

Answered By QuietMaple19 On

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.

Answered By CedarOrbit7 On

%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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.