Search code examples
arrayscpointersprintfc-strings

Shouldn't a character pointer array, print a pointer? Why does it print the string it is pointed to?


I have the code below:

    static char *name[] = {
            "January",
            "February",
            "March",
    };

    printf("%s", name[0]);

When I passed printf with name[0], it prints January. But shouldn't it print the address of January, since the array above stores a pointer to January?


Solution

  • The conversion specifier %s interprets the corresponding argument as a pointer to first character of a string that is outputted until the terminating zero character '\0' is encountered.

    If you want to output the pointer itself then you should write

    printf( "%p", ( void * )name[0] );
    

    Pay attention to that in this declaration

    static char *name[] = {
            "January",
            "February",
            "March",
    };
    

    the string literals used as initializers are implicitly converted to pointers to their first characters and these pointers are stored in the array name.