Printing a pointers value

前端 未结 5 2038
囚心锁ツ
囚心锁ツ 2021-01-14 21:25
#include 

int main(void)
{
   int x = 99;
   int *pt1;

   pt1 = &x;

   printf(\"Value at p1: %d\\n\", *pt1);
   printf(\"Address of p1 (with %%         


        
相关标签:
5条回答
  • 2021-01-14 21:46
    • 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.

    0 讨论(0)
  • 2021-01-14 21:46

    I don't know on dangers and downsides, but by using the %d notation you lose formatting for pointer like (12 vs 0x000012).

    0 讨论(0)
  • 2021-01-14 21:48

    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.

    0 讨论(0)
  • 2021-01-14 21:52

    %d displays an integer - there is no need for the size of a pointer to equal the size of an integer.

    0 讨论(0)
  • 2021-01-14 22:02

    If on your system pointers happen not to be the same size as ints, 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.

    0 讨论(0)
提交回复
热议问题