C++ · Strings
Character arrays and related functions
Distinguish C++ string length from character-array capacity, reserve room for the null terminator and check concatenation bounds.
Practice this topic in the app Read the lesson in the app
Length, capacity and the null terminator
char s[6] = "hello"; stores h, e, l, l, o, and the null character, occupying 6 positions in total.
strlen in <cstring> computes the length before the terminator, not including the terminator; strcmp compares in lexicographic order and returns a negative number, zero, or a positive number; strcpy copies, strcat appends, and the latter two require sufficient destination space.
sizeof(s) gives the total number of bytes for a local array, while strlen(s) is the current text length. After an array is passed to a function it often decays to a pointer, and sizeof can no longer be used on the parameter to find the original array capacity.
When reading input, set an upper limit on the input length, or use cin.getline(s, capacity). If the array has no terminator, string functions may continue reading out of bounds; in modern C++, string is usually more convenient.
Measuring length and reserving concatenation space
Example 1: Length and capacity are different
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[10] = "cat";
cout << strlen(s) << " " << sizeof(s) << endl;
cout << (strcmp(s, "cat") == 0) << endl;
}Output the first line 3 10, the second line 1. The terminator is not counted in the length, but it occupies array space.
Example 2: Reserve space for concatenation
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[8] = "abc";
const char tail[] = "de";
if (strlen(s) + strlen(tail) + 1 <= sizeof(s)) strcat(s, tail);
cout << s << endl;
}Output abcde. 3+2+1=6 positions are needed, and capacity 8 is sufficient; the extra 1 is the terminator.
Tips
- The result of strcmp is only guaranteed to be positive, negative, or zero, not guaranteed to be exactly 1 or −1.
- You cannot use s == t to compare the text content of two character arrays; you should use strcmp.
- strcpy and strcat do not automatically expand capacity; check the capacity first, then operate.
Prerequisites
Technical references
Scope note
This lesson is written by InfoCode and is not an official syllabus; the reference level is a site mapping and does not represent official levels, certification or eligibility. Practice records do not establish mastery or eligibility.
Reference level: GESP Level 3 (site mapping)