cstringpointerscharchar-pointer

How is a char pointer an entire string?


Let's say I have the following string:

char *my_string = "Stack";

As far as I know char * holds the memory address of the first character of the string "Stack". In the computer memory it might be represented as the following:

 ------------------------
| S | t | a | c | k | \0|
 ------------------------
  ^
  my_string

If I call: printf("%s\n", my_string);, the entire string is printed. How does the compiler know to print the entire string? Since as I understand, it only has an address of a character.


Solution

  • The char* indeed points only to the first character of your string, however functions like printf("%s") will simply start reading and continue until they find a 0-byte. String literals like your "Stack" example are zero-terminated by default, thus printf will know to print your string and stop after that.