Convert String to Array in C++

Copy a C++ string into a char array with strcpy, into a vector<char>, or with a manual loop. Learn why the array needs room for the '\0' terminator.

IntermediateString Conversion ProgramsExample 10 of 11
convert-string-to-array.cpp
1#include <iostream>
2#include <string>
3#include <vector>
4#include <cstring>
5using namespace std;
6
7int main() {
8 string str = "Hello";
9
10 // Method 1: Using c_str() and copying
11 char arr1[10];
12 strcpy(arr1, str.c_str());
13
14 // Method 2: Using vector of chars
15 vector<char> arr2(str.begin(), str.end());
16
17 // Method 3: Manual copying
18 char arr3[10];
19 for (int i = 0; i < str.length(); i++) {
20 arr3[i] = str[i];
21 }
22 arr3[str.length()] = '\0';
23
24 cout << "String: " << str << endl;
25 cout << "Array (method 1): " << arr1 << endl;
26
27 return 0;
28}

Sample Output

Array (method 1): Hello

arr1 printed as a C-string.

In this one

  • How strcpy copies c_str() into a char array
  • How vector<char> can be built from a string's iterators
  • How to copy characters by hand and add '\0'
  • How buffer size limits the copy

How it works

  1. 1

    str holds "Hello".

  2. 2

    strcpy copies 5 letters plus '\0' into arr1[10].

  3. 3

    vector<char> arr2 gets the 5 letters (no terminator).

  4. 4

    The loop copies into arr3 and writes '\0' at index 5.

  5. 5

    Only arr1 is printed.

Edge cases

String longer than the buffer

Set str to 15 characters with arr1[10].

strcpy writes past the end of arr1, which is undefined behavior and a classic security bug. Size the buffer as length + 1 or use a vector.

Printing a vector<char>

cout << arr2;

There is no << for vector, so this does not compile. Loop over it, or build a string from it.

What's going on

The program converts a C++ string (like "Hello") into a character array (like {'H', 'e', 'l', 'l', 'o', '\0'}). C++ strings are dynamic and managed, while character arrays are fixed-size and require manual memory management. This conversion bridges the gap between modern C++ strings and C-style character arrays.

Example:

Input string: "Hello"
Output array: char array containing "Hello" with null terminator

Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <string>
Essential for using the string data type.
3.#include <vector>
Provides vector container for dynamic arrays.
4.#include <cstring>
Provides C-style string functions like strcpy().

Declaring Variables

The program declares:

string str = "Hello";

string is the C++ string type that stores "Hello".
The string contains 5 characters: 'H', 'e', 'l', 'l', 'o'.
C++ strings automatically manage memory and include length information.

Method 1: Using c_str() and strcpy()

char arr1[10];

strcpy(arr1, str.c_str());

This is a common C-style method:

c_str() converts C++ string to C-style string (const char*).
strcpy() copies the C-style string into the character array.
Requires pre-allocated array with sufficient size.

How it works:

1.str.c_str() returns a pointer to a null-terminated character array.
2.strcpy(destination, source) copies the string including the null terminator.
3.The array must be large enough to hold the string plus null terminator.

Advantages:

Simple and familiar (C-style approach)
Direct array access
Compatible with C functions

Disadvantages:

Requires manual size management
Risk of buffer overflow if array is too small
No automatic bounds checking

Important: The array size (10) must be at least str.length() + 1 to accommodate the null terminator.

Method 2: Using Vector

vector<char> arr2(str.begin(), str.end());

This method uses a C++ vector:

vector is a dynamic array that automatically manages memory.
str.begin() and str.end() are iterators pointing to the start and end of the string.
Creates a vector containing all characters from the string.

How it works:

1.str.begin() returns iterator to first character.
2.str.end() returns iterator past the last character.
3.vector constructor copies all characters from the iterators.

Advantages:

Automatic memory management
Dynamic size - no need to specify size beforehand
Safe - no buffer overflow risk
Modern C++ approach

Disadvantages:

Slightly more overhead than fixed arrays
Not a true C-style array (but can access with .data())

Example:

vector<char> vec(str.begin(), str.end());

// Access: vec[0], vec[1], etc.

// Size: vec.size()

Method 3: Manual Copying

char arr3[10];

for (int i = 0; i < str.length(); i++) {

arr3[i] = str[i];

}

arr3[str.length()] = '\0';

This method manually copies each character:

Uses a loop to copy characters one by one.
Manually adds the null terminator at the end.
Full control over the copying process.

How it works:

1.Loop through each character in the string.
2.Copy each character to the corresponding array position.
3.Add null terminator ('\0') at the end to make it a valid C-string.

Advantages:

Full control over the process
Educational - shows how copying works
Can add custom logic during copying

Disadvantages:

More code to write
Easy to forget the null terminator
Manual bounds checking required

Other Methods (Mentioned but not shown in code)

Method 4: Using copy() Algorithm

#include <algorithm>

char arr4[10];

copy(str.begin(), str.end(), arr4);

arr4[str.length()] = '\0';

Uses STL copy() algorithm.
Copies from string iterators to array.
Still need to add null terminator manually.

Method 5: Using string data() Method

char* arr5 = new char[str.length() + 1];

strcpy(arr5, str.data());

// Remember to delete[] arr5 when done

data() returns pointer to string's internal array.
Requires dynamic allocation.
Must manually manage memory (delete[]).

Displaying Results

The program prints:

cout << "String: " << str << endl;

cout << "Array (method 1): " << arr1 << endl;

Output:

String: Hello

Array (method 1): Hello

The array is printed as a C-string, which automatically stops at the null terminator.

Important Considerations

Null Terminator:

C-style strings must end with '\0' (null terminator).
Without it, string functions won't know where the string ends.
Always ensure array size is at least length + 1.

Buffer Size:

Array must be large enough: size >= string.length() + 1.
Buffer overflow occurs if array is too small.
Use str.length() + 1 to calculate required size.

Memory Management:

Fixed arrays: Automatic (stack-allocated).
Dynamic arrays: Manual (must delete[]).
Vectors: Automatic (handled by vector).

When to Use Each Method

c_str() + strcpy(): When you need a fixed-size C-style array and know the maximum size.
Vector: When you need dynamic size or want automatic memory management (recommended).
Manual Copying: When you need custom logic during copying or want to understand the process.
copy() Algorithm: When you prefer STL algorithms and want clean code.
data() Method: When you need direct access to string's internal buffer (advanced use).

Best Practice: Use vector for most cases - it's safe and modern. Use fixed arrays only when size is known and fixed.

Safety Considerations

Buffer Overflow Prevention:

Always check string length before copying.
Ensure array size is sufficient.
Consider using strncpy() with size limit for safer copying.

Example with Safety Check:

const int MAX_SIZE = 10;

if (str.length() < MAX_SIZE) {

strcpy(arr, str.c_str());

} else {

// Handle error - string too long

}

Modern Alternative:

Prefer vector or use strncpy() with size limits.
Consider using string instead of char arrays when possible.

Accessing Array Elements

After conversion, access characters like a normal array:

char arr[10];

strcpy(arr, str.c_str());

// Access individual characters

char first = arr[0]; // 'H'

char second = arr[1]; // 'e'

// Iterate through array

for (int i = 0; arr[i] != '\0'; i++) {

cout << arr[i];

}

return 0;

This ends the program successfully.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Minimum char array size to hold "Hello" as a C-string?

Pick an answer to check it.

Question 2

What does vector<char> v(s.begin(), s.end()) contain for s = "Hi"?

Pick an answer to check it.

Questions people ask

Why only print arr1?

The other two are built to show the methods. You can print arr3 the same way since it has a terminator.

Why does the loop use str.length()?

To copy every character; then it adds '\0' at that index to end the C-string.

Is there a safer strcpy?

Use the string's copy method or strncpy with care, or avoid raw arrays and keep std::string.