Is %p specifier only for valid pointers?

前端 未结 4 1410
失恋的感觉
失恋的感觉 2021-02-12 12:47

Suppose on my platform sizeof(int)==sizeof(void*) and I have this code:

printf( \"%p\", rand() );

Will this be undefined behavior

4条回答
  •  面向向阳花
    2021-02-12 13:24

    %p is just a output format specification for printf. It doesn't need to dereference or validate the pointer in any way, although some compilers issue a warning if the type is not a pointer:

    int main(void)
    {
        int t = 5;
        printf("%p\n", t);
    }
    

    Compilation warning:

    warning: format ‘%p’ expects argument of type ‘void*’, but argument 2 has type ‘int’ [-Wformat]
    

    Outputs:

    0x5
    

提交回复
热议问题