1

I understand that in C, a string is an array of characters with a special '\0' character at the end of the array.

Say I have "Hello" stored in a char* named string and there is a '\0' at the end of the array.

When I call printf("%s\n", string);, it would print out "Hello".

My question is, what happens to '\0' when you call printf on a string?

Mayur
  • 2,583
  • 16
  • 28
drumGod31
  • 51
  • 2
  • 8
  • 6
    Nothing. it's just an indicator so printf knows when to stop printing chars. – doubleE Oct 01 '18 at 19:42
  • what if '\0' is not included in the array and you call printf on it? – drumGod31 Oct 01 '18 at 19:43
  • 3
    then you have a bug :) – OznOg Oct 01 '18 at 19:43
  • 2
    @drumGod31 It will keep printing until it encounters a '\0' or until you get a segfault. – lakshayg Oct 01 '18 at 19:43
  • 1
    "what if '\0' is not included in the array" --> tell when to stop `printf("%.*s\n", max_characters_to_printf, array_without_null_chracter)` – chux - Reinstate Monica Oct 01 '18 at 19:47
  • See also: https://stackoverflow.com/questions/13656377/how-come-printf-is-printing-a-non-null-terminated-string?noredirect=1&lq=1 – lakshayg Oct 01 '18 at 19:47
  • 1
    @drumGod: The `%s` conversion specifier basically means, "print the sequence of characters starting at the specified location until you encounter a string terminator"; if there's no string terminator in the array you passed, then `printf` will keep printing characters from the memory past that array until it sees the terminator. – John Bode Oct 01 '18 at 19:48

1 Answers1

2

The null character ('\0') at the end of a string is simply a sentinel value for C library functions to know where to stop processing a string pointer.

This is necessary for two reasons:

  1. Arrays decay to pointers to their first element when passed to functions
  2. It's entirely possible to have a string in an array of chars that doesn't use up the entire array.

For example, strlen, which determines the length of the string, might be implemented as:

size_t strlen(char *s)
{
     size_t len = 0;
     while(*s++ != '\0') len++;
     return len;
}

If you tried to emulate this behavior inline with a statically allocated array instead of a pointer, you still need the null terminator to know the string length:

char str[100];
size_t len = 0;

strcpy(str, "Hello World");
    
for(; len < 100; len++)    
    if(str[len]=='\0') break;

// len now contains the string length

Note that explicitly comparing for inequality with '\0' is redundant; I just included it for ease of understanding.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85