C-Style Strings
Lesson outline
What are C-Style Strings?
C-style strings are character arrays that end with a null terminator (\0). They come from the C language and remain available in C++ mainly for compatibility.
Unlike the safer and more flexible std::string class, C-style strings require careful manual handling of size and termination. Many common errors (buffer overflows, missing terminator) stem from incorrect bounds management.
Declaration and Initialization
C-style strings can be declared and initialized in different ways:
String Literals Are Read-Only
In C++, string literals have type const char[N]. You cannot modify them.
Common Functions (<cstring>)
The C header <cstring> provides standard functions for manipulating C-style strings. They all expect a null-terminated string.
Safer Copies/Appends
When you must stay with C APIs, prefer sized operations and ensure termination yourself. Alternatively, use std::snprintf.
Converting Between C and C++ Strings
You can construct std::string from a C string, and you can obtain a C string from std::string via c_str().