Just don't rain
Just don't rain

Reputation: 66

Use strcpy to transform a C++ string to a Char array

For some reason, I was trying to covert a C++ string to a char array. Below is what I did:

string aS="hello world";
char aC[aS.size()];
strcpy(aC, aS.c_str());
cout << aC[0] << endl;

string bS="veooci  m eode owtwolwwwwtwwj mooawee mdeeme  eeeec eme aemmeledmll llllleolclclcmslococecewaccocmelaeaccoaaooojutmjooooocoemoooealm omjcdmcmkemmdemmmiwecmcmteeeote eoeeeem   ecc e  yolc e w    dtoooojttttmtwtt ttjcttoowl otdooco ko mooooo  aowmemm o  et  jmc    cmlctmmcccjcccecomatocooccoeoclooomoecwooo mcdoo dcdco dddooedoemod eddeedoedje  emadleweemeeedeeeec   or o  m  wejeetoj    o ojjjlwdjjjj mjmceaeoaai laaadoaa aetmotaemmj  mmmmmmlmm cmol c  mwoaoe omav";

char bC[bS.size()];
strcpy(bC, bS.c_str());
cout << aC[0] << endl;

When aC[0] was first called, it gave 'h' as expected. However, when aC[0] is called at the second time, it gave ''. Could someone explain me what happened here?

Upvotes: 2

Views: 7670

Answers (4)

PaulMcKenzie
PaulMcKenzie

Reputation: 35454

I can see some utility of changing to an array if you're calling a function that will change the string buffer (pre C++11). Otherwise, use the other solutions such as c_str() if the buffer is not going to be changed.

However, if you really wanted a char array due to the buffer possibly being changed, use std::vector<char>. This will bypass the issue of using non-standard syntax (aC[aS.size()]), and removes the need to dynamically allocate memory. A std::vector<char> effectively is a changeable string buffer, only wrapped.

#include <vector>
#include <string>
#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    string aS="hello world";
    std::vector<char> aC(aS.begin(), aS.end());  // copy
    aC.push_back(0);  // null-terminate
    cout << &aC[0] << endl;
}

Output:

hello world

Now, where you need to specify a character array pointer, you just pass the address of the first element in the vector (provided that the vector is not empty).

Live Example: http://ideone.com/tF32Zt

Upvotes: 1

Paul R
Paul R

Reputation: 213060

char aC[aS.size()];

would need to be:

char aC[aS.size() + 1];

in order to allow for the terminating '\0' required for a C string.

Upvotes: 4

vsoftco
vsoftco

Reputation: 56567

If you don't want to use the std::string::c_str() member function, you should then allocate the char array dynamically, as you cannot declare variable length arrays in C++, such as:

char* bC = new char[aS.size() + 1]; // don't forget to delete[]
strcpy(bC, bS.c_str());

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117926

For some reason, I was trying to covert a C++ string to a char array

Why don't you just use .c_str(), it does this for you

string aS="hello world";
cout << aS.c_str();

Upvotes: 6

Related Questions