warning: format ‘%p’ expects argument of type ‘void *’, but argument 3 has type ‘char **’

前端 未结 3 1145
孤街浪徒
孤街浪徒 2021-01-18 04:59

I\'m trying to print out the value of argv at this point in my code, but when I try to compile it, I get warning: format ‘%p’ expects argument of type ‘vo

相关标签:
3条回答
  • 2021-01-18 05:19

    In order to print argv and it's address you need to do

    int main(int argc, char* argv[])
    {
        int i;
        printf("address of argv = %p\n", (void *)argv);
        for (i = 0; i < argc; ++i)
        {
            printf("%s\n", argv[i]);
        }
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-18 05:25

    Well, not any pointer (type).

    According to C11, chapter §7.21.6.1, for the %p conversion specifier,

    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.

    So, the argument must be of type void * (or, a char*, given they have the same alignment requirements). Any other type of pointers, must be converted through an explicit cast, as there is no default argument promotion for pointers.

    Something like

    printf("%s%p", "argv = ", (void *)argv);
    

    should do.

    0 讨论(0)
  • 2021-01-18 05:31

    So why don't you cast it?

    printf("argv = %p\n", (void *)argv);`
    

    The %p pointer is specified (POSIX printf(); C11 §7.21.6.1 The fprintf function):

    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.

    Since char ** is not a void *, you need to do the explicit conversion. The compiler isn't allowed by the standard to do the conversion to void * for you — the ellipsis notation in the declaration of printf() means that default argument promotions occur, but that affects only the float type and integer types smaller than int (short, char, etc).

    On most machines these days, that's a no-op. On the (long obsolete) machine where I learned to program in C, there weren't void * yet (too old for the standard), but the equivalent was char *, and the value of a char * address for a given memory location was different from the pointer value for any other type — the casts were not optional.

    Note that I'm assuming you intend to print the value of the address. If you intend to print the contents, then there's more work to be done.

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