#include <stdio.h>
int main(void)
{
int x = 99;
int *pt1;
pt1 = &x;
printf("Value at p1: %d\n", *pt1);
printf("Address of p1 (with %%p): %p\n", pt1);
printf("Address of p1 (with %%d): %d\n", pt1);
return 0;
}
What are the downsides/d开发者_运维技巧angers to printer pointer values with %d
instead of %p
?
%d displays an integer - there is no need for the size of a pointer to equal the size of an integer.
sizeof( int * ) need not be equal to sizeof( int )
the library implementation is free to use a different, more appropriate presentation of the pointer value (e.g. hexadecimal notation).
%p is simply "the right thing to do". It's what the standard says should be used for pointers, while using %d is misusing the integer specifier.
Imagine what happens when someone refactors your code, and somewhat over-enthusiastically exchanges all "int" with "long" and all "%d" with "%ld"... oops.
If on your system pointers happen not to be the same size as int
s, you can cause an unlimited amount of screwage. If they happen to be the same size, then you're probably safe. As far as the language standards go, though, passing a pointer and treating it as an integer is allowed to set fire to your computer, send pornographic email to your boss, or cause demons to fly out of your nose. It probably won't do any of those things, but it could conceivably print out misleading values or something.
Don't do this. Use %p
unless you have a desperate need to treat the address as an integer (note: you probably don't); in that case, actually cast it to an integer type so that you aren't abusing the argument-passing mechanism.
In addition to the dangers pointed out in other answers, some compilers (e.g. gcc with format-string warnings turned on) will generate a warning that you're passing a pointer to %d
, which expects an int
.
I don't know on dangers and downsides, but by using the %d notation you lose formatting for pointer like (12 vs 0x000012).
精彩评论