String basics
- C course
- Beginner
- Lesson 59/116
- 4 min
Learn C strings with char arrays and the null terminator.
A string is a char array
C has no separate string type. A string is a char array that ends with a null character ('\0'). This character tells functions where the string ends.
char name[5] = {'A', 'l', 'i', '\0'};
printf("%s", name); /* prints Ali */Even though the array has 4 slots, '\0' takes one; so a 3-letter name needs a 4-element array. The %s format specifier prints characters up to '\0'.
Printing a string with %s
The printf function prints a char array as a string using the %s format specifier. It reads up to '\0' and ignores the rest.
char city[] = "Berlin";
printf("City: %s\n", city);
/* City: Berlin */If the array has data after '\0', %s does not print it. So sizing the array and placing the terminator correctly matter.
Practice First string: print a name from a char array
Declare a char array holding 'A', 'l', 'i' followed by '\0'. Print it with printf and %s; the output should be Ali.
Starter code
#include <stdio.h>
int main(void) {
/* declare char array */
/* print with printf %s */
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
char name[] = {'A', 'l', 'i', '\0'};
printf("%s\n", name);
return 0;
}Expected output
Ali
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many elements does a char array need to hold the 3-letter string "Ali"?
char name[?] = "Ali";- 2
- 3
- 5
- 4 Correct answer
Explanation: You need room for 3 letters plus the null character; 4 elements total.
2 Null terminator in a char array
char end = ____; /* string terminator */
char end = '\0'; /* string terminator */
Explanation: '\0' is the null character that marks the end of a string.
3 Match the string concepts
| Term | Meaning |
|---|---|
char |
character type |
\0 |
string terminator |
%s |
string format specifier |
printf |
output function |