Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: initialize char array with a string?

Tags:

c++

arrays

string

Let's say I have a string called garbage.

Whatever's in garbage, I want to make a char array out of it. Each element would be one char of the string.

So, code would be similar to:

const int arrSize = sizeof(garbage); //garbage is a string
char arr[arrSize] = {garbage};

But, this will give an error "cannot convert string to char in initialization".

What is the correct way to do this? I just want to feed the darn thing a string and make an array out of it.

like image 395
derp Avatar asked Dec 03 '22 01:12

derp


2 Answers

C++ std::string maintains an internal char array. You can access it with the c_str() member function.

#include <string>
std::string myStr = "Strings! Strings everywhere!";
const char* myCharArr = myStr.c_str();

Keep in mind that you cannot modify the internal array. If you want to do so, make a copy of the array and modify the copy.

like image 82
Matt Kline Avatar answered Dec 20 '22 19:12

Matt Kline


I think what you're after is a lot simpler:

char arr[] = "some interesting data (garbage)";
like image 23
JJ on SE Avatar answered Dec 20 '22 18:12

JJ on SE