Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 671
Just don't rain Avatar asked Apr 15 '26 00:04

Just don't rain


2 Answers

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();
like image 51
Cory Kramer Avatar answered Apr 16 '26 16:04

Cory Kramer


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.

like image 35
Paul R Avatar answered Apr 16 '26 16:04

Paul R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!