C-Style Strings
Null-terminated character arrays
cstring_basics.cpp
#include <iostream>
int main() {
char str1[] = "hello"; // size automatically becomes 6 (5 + '\0')
char str2[10] = "hi"; // explicit size, rest is zero-filled
char str3[] = {'h', 'i', '\0'}; // manual construction, same as "hi"
std::cout << str1 << std::endl;
for (int i = 0; str1[i] != '\0'; i++) {
std::cout << str1[i];
}
std::cout << std::endl;
return 0;
}The <cstring> function library
Function | Purpose |
|---|---|
strlen(s) | Returns the length of s, not counting the null terminator |
strcpy(dest, src) | Copies src into dest, including the null terminator |
strcat(dest, src) | Appends src onto the end of dest |
strcmp(a, b) | Returns 0 if equal, negative if a < b, positive if a > b |
strncpy(dest, src, n) | Copies at most n characters from src into dest |
cstring_functions.cpp
#include <cstring>
#include <iostream>
int main() {
char greeting[20] = "Hello, ";
char name[] = "World!";
std::cout << "Length: " << strlen(greeting) << std::endl;
strcat(greeting, name); // greeting now holds "Hello, World!"
std::cout << greeting << std::endl;
if (strcmp(greeting, "Hello, World!") == 0) {
std::cout << "Strings match!" << std::endl;
}
return 0;
}buffer_overflow_danger.cpp
char small[6]; strcpy(small, "This string is way too long"); // undefined behavior: overflow!
strncpy — safer, but still tricky
strncpy_caveat.cpp
char dest[6]; strncpy(dest, "HelloWorld", 5); // copies "Hello", but does NOT add '\0' dest[5] = '\0'; // you must terminate it yourself
Why modern C++ uses std::string instead
Automatic memory management — no fixed-size buffer to overflow, and no manual
deleterequired.Knows its own length — no scanning for a null terminator just to find the size.
Operator support — concatenate with
+, compare with==, all without calling separate functions.Works seamlessly with the STL — streams, containers, and algorithms all understand it natively.