Lesson 55 +10 XP

C-Style Strings

C-Style Strings

Before std::string, C (and early C++) stored text in character arrays. You will still see them in old code and in the <cstring> library.

A char array with a secret ending

char text[] = "hi";

This is really an array of three char: 'h', 'i', and a hidden '\0'. The null terminator marks where the string ends. That is why the array holds 3 chars, not 2.

Under the hood

char word[4] = {'h', 'i', '\0'};   // one slot left over, that's fine

\0 is a real character with the value 0. C functions stop reading when they hit it.

Measuring with strlen

#include <cstring>
cout << strlen("hello") << endl;   // 5

strlen counts characters up to the null terminator - it does not count \0 itself.

Why std::string is the modern pick

string word = "hi";              // no \0 worry, it handles it
string joined = word + " there"; // easy to combine
word.size();                     // easy to measure

std::string manages its own memory, grows as needed, and comes with +, size(), and safe access. C-style strings are small and fast but easy to break. Use std::string unless you have a reason not to.

TL;DR

  • A C-style string is a char array ending in '\0'.
  • The null terminator marks the string's end.
  • strlen counts characters, excluding \0.
  • std::string is easier and safer; prefer it.