C-Style Strings
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:
#include <iostream>
using namespace std;
int main() {
char str1[] = "Hello"; // Compiler adds null terminator; size is 6
char str2[6] = {'H','e','l','l','o','\0'}; // Explicit terminator
cout << str1 << '\n' << str2;
return 0;
}
Hello Hello
String Literals Are Read-Only
In C++, string literals have type const char[N]
. You cannot modify them.
#include <iostream>
using namespace std;
int main() {
const char* p = "Hello"; // OK: pointer to read-only literal
// p[0] = 'h'; // ❌ Error: cannot modify a string literal
cout << p;
return 0;
}
Hello
Common Functions (<code><cstring></code>)
The C header <cstring>
provides standard functions for manipulating C-style strings. They all expect a null-terminated string.
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char src[] = "Source";
char dest[20];
std::strcpy(dest, src); // Copy string (no bounds check!)
std::strcat(dest, "+"); // Append (no bounds check!)
size_t len = std::strlen(dest); // Get length (up to '\0')
int cmp = std::strcmp(dest, "Source+"); // Compare
cout << dest << " (length: " << len << ")\n";
cout << "compare==0? " << (cmp == 0);
return 0;
}
Source+ (length: 7) compare==0? 1
Safer Copies/Appends
When you must stay with C APIs, prefer sized operations and ensure termination yourself. Alternatively, use std::snprintf
.
#include <cstdio>
#include <cstring>
int main() {
char dest[10] = {};
const char* a = "Hi";
const char* b = "-there";
// Option 1: snprintf (recommended among C APIs)
std::snprintf(dest, sizeof(dest), "%s%s", a, b); // truncates safely if needed
// Option 2: strncpy/strncat (be careful: strncpy may not add '\0' on truncation)
char d2[10] = {};
std::strncpy(d2, a, sizeof(d2) - 1); // force termination space
std::strncat(d2, b, sizeof(d2) - 1 - std::strlen(d2));
return 0;
}
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()
.
#include <iostream>
#include <string>
using namespace std;
int main() {
const char* cstr = "C-style string";
string cpp = cstr; // C -> C++
const char* back = cpp.c_str(); // C++ -> C (read-only view)
cout << cpp << '\n' << back;
return 0;
}
C-style string C-style string