How to printf a memory address in C

后端 未结 2 1038
名媛妹妹
名媛妹妹 2020-11-28 13:53

My code is:

#include 
#include 

void main()
    {
    char string[10];
    int A = -73;
    unsigned int B = 31337;

    strc         


        
2条回答
  •  天涯浪人
    2020-11-28 14:57

    Use the format specifier %p:

    printf("variable A is at address: %p\n", (void*)&A);
    

    The standard requires that the argument is of type void* for %p specifier. Since, printf is a variadic function, there's no implicit conversion to void * from T * which would happen implicitly for any non-variadic functions in C. Hence, the cast is required. To quote the standard:

    7.21.6 Formatted input/output functions (C11 draft)

    p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

    Whereas you are using %x, which expects unsigned int whereas &A is of type int *. You can read about format specifiers for printf from the manual. Format specifier mismatch in printf leads to undefined behaviour.

提交回复
热议问题