Correct format specifier to print pointer or address?

前端 未结 5 1702
自闭症患者
自闭症患者 2020-11-21 13:17

Which format specifier should I be using to print the address of a variable? I am confused between the below lot.

%u - unsigned integer

%x

5条回答
  •  眼角桃花
    2020-11-21 13:45

    Use %p, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u expects an unsigned int, but what if void* has a different size or alignment requirement than unsigned int?)

    *) [See Jonathan's fine answer!] Alternatively to %p, you can use pointer-specific macros from , added in C99.

    All object pointers are implicitly convertible to void* in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):

    printf("x lives at %p.\n", (void*)&x);
    

提交回复
热议问题