-1

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);
}
  • 1
    A string in C is a sequential series of characters leading up the first null char. So while you are correct that `s` points to the address that stores `H`, it's more correct to say that it points also points to an array of characters: `{'H', 'I', '!', '\0'}`. The `%s` format specifier tells `printf` to include every char starting at address `s` up to the first null char. – selbie Aug 02 '22 at 08:31
  • 1
    The `printf` function is the tip of the iceberg. Underneath of it there are tons of subroutines depending on the formatting string. That is, when you put a `%s` formatter the `printf` will look for a `char` type **pointer** in the arguments because it needs to use that pointer internally. – Kozmotronik Aug 02 '22 at 08:35
  • 1
    It looks like you want a tutorial on how arrays, pointers, and strings work in C. Stack Overflow isn't the place for that. – Tom Karzes Aug 02 '22 at 09:02
  • `printf` *always* expects a pointer, so passing your pointer `s` to it is totally fine. You might find [this answer](https://stackoverflow.com/questions/50074855/the-usage-of-an-ampersand-in-printf-and-format-specifiers/50075252#50075252) useful (although it's talking about a different issue). – Steve Summit Aug 02 '22 at 12:47

2 Answers2

0

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

FXPoWer_
  • 5
  • 3
  • I mean, why when we put in an adress of the first character of a string and don't dereference it, C will still print out what is inside of this adress – Valdemarcheck Aug 02 '22 at 10:24
0
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.

John Bode
  • 119,563
  • 19
  • 122
  • 198