1

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?

4
  • printf's %s format wants a pointer. Your name array is an array of pointers. So name[0] is a pointer, and everyone's happy. (And, more specifically, %s wants, and name[0] is, a pointer to char, that points to the beginning of a valid, null-terminated string.) Commented Oct 18, 2021 at 16:17
  • If you want address, use %p. Commented Oct 18, 2021 at 16:18
  • See this recent question for some possibly-relevant information. Commented Oct 18, 2021 at 16:19
  • name[0] stores a pointer to the first character of a non-modifiable, anonymous array of char that is the string literal "January". Commented Oct 18, 2021 at 16:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.