C Strings

In C there is no dedicated string type like in some other languages. Instead, a string is simply an array of characters that ends with a special hidden character called the null terminator, written as backslash zero. Understanding this one idea explains almost everything about how strings behave in C.

Creating a String

The easiest way to make a string is to use a char array and assign it a value in double quotes. C automatically adds the null terminator at the end, so you do not have to write it yourself.

A simple string

#include <stdio.h>

int main() {
  char greeting[] = "Hello";
  printf("%s\n", greeting);
  return 0;
}
Note: The %s format specifier is used to print strings. It keeps printing characters until it reaches the null terminator, which is why that hidden character matters so much.

Strings Are Character Arrays

Because a string is really an array, you can reach individual letters using an index, exactly like any other array. The word Hello uses indexes 0 through 4, and index 5 holds the null terminator.

Accessing single characters

#include <stdio.h>

int main() {
  char greeting[] = "Hello";
  printf("First letter: %c\n", greeting[0]);
  greeting[0] = 'J';
  printf("Now it says: %s\n", greeting);
  return 0;
}

How "Hello" is stored

IndexCharacter
0H
1e
2l
3l
4o
5\0 (null terminator)

Looping Through a String

You can walk through a string one character at a time with a loop. A common trick is to keep going until you hit the null terminator, which marks the true end of the text.

Printing each character

#include <stdio.h>

int main() {
  char word[] = "Code";
  for (int i = 0; word[i] != '\0'; i++) {
    printf("%c\n", word[i]);
  }
  return 0;
}
Note: Always make sure a char array is big enough to hold your text plus the null terminator. A string of 5 letters needs an array of at least 6 characters.

Exercise: C Strings

How does C actually represent a string in memory?