C Strings
A string is text stored as a row of chars. C has no text type of its own, so text lives in a char array with an end mark.
Letters and the end mark
The row holds A, d, a, and the end mark. The print lines show 65 for A and 0 for the end mark.
#include <stdio.h>
int main() {
char name[4] = {'A', 'd', 'a', '\0'};
printf("%d\n", name[0]);
printf("%d\n", name[3]);
return 0;
}Double quotes add the end mark
Hello in double quotes fills five slots, and the end mark lands in slot 5 by itself. The print lines show 111 for o and 0 for the end mark.
#include <stdio.h>
int main() {
char word[6] = "Hello";
printf("%d\n", word[4]);
printf("%d\n", word[5]);
return 0;
}Change one letter
The first letter changes from H to J. The print lines show 74 for J and 111 for the last letter, o.
#include <stdio.h>
int main() {
char word[6] = "Hello";
word[0] = 'J';
printf("%d\n", word[0]);
printf("%d\n", word[4]);
return 0;
}Example
#include <stdio.h>
int main() {
char greeting[6] = "Hello";
int len = 0;
while (greeting[len] != '\0') {
len = len + 1;
}
printf("%d\n", len);
return 0;
}Key points
- A string is a char array, a row of chars under one name.
- char name[4] holds the text Ada, with one slot for each letter and one slot for the end mark.
- The end mark is the char \0, and its value is 0.
- A string written in double quotes adds the end mark by itself.
- char word[6] = "Hello"; holds five letters and the end mark.
- One letter can be changed like any other value in a row.
- A loop can walk a string until it meets the end mark.
Greeting holds Hello, five letters and an end mark. A loop counts letters until it meets the end mark, and the print line shows 5.
Note
Leave one slot spare for the end mark, or the text has no end.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What sits in the last slot of a string?