Home > Software engineering >  Why printf works as intended here?
Why printf works as intended here?

Time:08-02

Why does this code actually print out "HI!" ? char *s is an adress to the first character of a string, so in the next line of code when we put variable s into printf it should return an adress to that character to printf which obviously can't be represented as a string with %s. But it does. Why?

#include <stdio.h>

int main(void)
{
        char *s = "HI!";
        printf("%s\n", s);
}

CodePudding user response:

if you want to print the adress, you have to write printf("%p\n", s); instead of printf("%s\n", s);

CodePudding user response:

7.21.6.1 The fprintf function
...
8 The conversion specifiers and their meanings are:
...
s      If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type.280) Characters from the array are written up to (but not including) the terminating null character. If the precision is specified, no more than that many bytes are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null character.
...
280) No special provisions are made for multibyte characters.
C 2011 Online Draft

The %s conversion specifier expects a pointer to the first character of a string - it will print that character and all characters following it until it sees the 0 terminator.

When you pass an array expression as an argument:

char s[] = "Hi!";
printf( "%s\n", s );

that array expression "decays" to a pointer to the first element.

  • Related