CITS2002 Systems Programming  
next CITS2002 CITS2002 schedule  

Strings are terminated by a special character

Unlike other arrays in C, the support for character arrays is extended by treating one character, the null byte, as having special significance.
We may specify the null byte, as in the example:

   array[3] = '\0';

The null byte is used to indicate the end of a character sequence, and it exists at the end of all strings that are defined within double-quotes.

Inside the computer's memory we have:

h e l l o \0
Of note, when dealing with strings:

  • the string requires 6 bytes of memory to be stored correctly, but
  • functions such as strlen(), which calculate the string's length, will report it as 5.

There is no inconsistency here - just something to watch out for.

Because the null byte has special significance, and because we may think of strings and character arrays as the same thing, we can manipulate the contents of strings by changing the array elements. Consider:

h e l l o   w o r l d \0

If we execute the statement:

   array[5] = '\0';

the space between the two words is replaced by the null byte.
The result is that the array still occupies 12 bytes of storage, but if we tried to print it out, we would only get hello.


CITS2002 Systems Programming, Lecture 6, p7, 8th August 2023.