drumGod31
drumGod31

Reputation: 51

Printing a string in C

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?

Upvotes: 1

Views: 4523

Answers (1)

Govind Parmar
Govind Parmar

Reputation: 21532

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.

Upvotes: 2

Related Questions