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;
}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
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;
}Exercise: C Strings
How does C actually represent a string in memory?