K
Keith Thompson
Peter Nilsson said:How often is this useful? When it is, how useful is %p?
Printing pointer values probably useful very often, but I like having
"%p" for those cases where it is useful.
Having printed a pointer with %p, how does a program guarantee
that subsequent printed characters will not undermine scanf's
ability to reconstitute a comprable pointer value?
I must admit I've used *printf and *scanf to print and reconstitute a
pointer value. But with reasonable precautions, such as printing the
value at the end of a line with something recognizable in front of it,
I wouldn't have any qualms about assuming that the output format will
be reasonable. A new-line character in the middle of the result would
mess this up, but I'm content to count on vendors not to do something
that silly.
If I do something like...
printf("ptr is %p\n", (void *) ptr);
...what is the guarantee that the output won't exceed an
implementation's limit on text line width?
There's no actual guarantee of this, but again, I'm willing to assume
reasonable behavior. Having the output of "%p" exceed the maximum
text line length is hardly the only silly but legal thing a perverse
implementation could do.
When I do print pointers, I hex dump the representation.
It's the only way to gain full control over the output.
#include <stdio.h>
#include <limits.h>
#define CHAR_NIBBLE ((CHAR_BIT + 3) / 4)
void dump_ptr(FILE *fp, const void *ptr)
{
const unsigned char *p = (const unsigned char *) &ptr;
size_t i;
for (i = 0; i < sizeof ptr; i++)
fprintf(fp, "%0*X", CHAR_NIBBLE, (unsigned) *p++);
}
Sure, that works too. On the other hand, on some systems it's
traditional to show addresses in octal rather than in hexadecimal; on
others, address might be segmented, and your method loses the
distinction between the discrete pieces of the address, something that
"%p" would probably capture.
And it prints the bytes backwards on a little-endian system.
Also, if two different representations represent the same address
(possible in a segmented addressing system), "%p" could at least
potentially normalize them.