C++ How to Convert String to Char Array Easily
std::string to a char array by using str.copy(charArray, length) or by accessing the string's internal buffer with stringVar.data() or stringVar.c_str().Examples
How to Think About It
Algorithm
Code
#include <iostream> #include <string> int main() { std::string str = "hello"; char charArray[6]; // length of str + 1 for '\0' str.copy(charArray, str.size()); charArray[str.size()] = '\0'; // null terminate std::cout << "Char array: " << charArray << std::endl; return 0; }
Dry Run
Let's trace converting the string "hello" to a char array.
Input string
str = "hello"
Create char array
charArray size = 6 (5 chars + 1 null)
Copy characters
charArray = ['h','e','l','l','o', '\0']
| Index | charArray[Index] |
|---|---|
| 0 | h |
| 1 | e |
| 2 | l |
| 3 | l |
| 4 | o |
| 5 | \0 |
Why This Works
Step 1: Using std::string::copy
The copy method copies characters from the string to the char array but does not add a null terminator.
Step 2: Adding null terminator
You must manually add '\0' at the end of the char array to mark the end of the string for C-style strings.
Step 3: Printing char array
Printing the char array works like printing a C-string because of the null terminator.
Alternative Approaches
#include <iostream> #include <string> int main() { std::string str = "hello"; const char* charArray = str.c_str(); std::cout << "Char array: " << charArray << std::endl; return 0; }
#include <iostream> #include <string> #include <vector> int main() { std::string str = "hello"; std::vector<char> charVec(str.begin(), str.end()); charVec.push_back('\0'); std::cout << "Char array: " << &charVec[0] << std::endl; return 0; }
Complexity: O(n) time, O(n) space
Time Complexity
Copying each character from the string to the char array takes linear time proportional to the string length.
Space Complexity
The char array requires extra space equal to the string length plus one for the null terminator.
Which Approach is Fastest?
Using c_str() is fastest as it avoids copying, but the array should not be modified. Copying creates a separate modifiable array.
| Approach | Time | Space | Best For |
|---|---|---|---|
| std::string::copy | O(n) | O(n) | Modifiable char array |
| std::string::c_str() | O(1) | O(1) | Read-only access, no copy |
| std::vector | O(n) | O(n) | Dynamic size, safe modification |