Ptichka
Ptichka

Reputation: 295

How do I convert a string to a char* in c++?

I have an error in my program: "could not convert from string to char*". How do I perform this conversion?

Upvotes: 22

Views: 35454

Answers (7)

user325117
user325117

Reputation:

If you can settle for a const char*, you just need to call the c_str() method on it:

const char *mycharp = mystring.c_str();

If you really need a modifiable char*, you will need to make a copy of the string's buffer. A vector is an ideal way of handling this for you:

std::vector<char> v(mystring.length() + 1);
std::strcpy(&v[0], mystring.c_str());
char* pc = &v[0];

Upvotes: 28

Vatsan
Vatsan

Reputation: 1173

//assume you have an std::string, str. 
char* cstr = new char[str.length() +1]; 
strcpy(cstr, str.c_str()); 

//eventually, remember to delete cstr
delete[] cstr; 

Upvotes: 9

Dialecticus
Dialecticus

Reputation: 16761

If const char* is good for you then use this: myString.c_str()

If you really need char* and know for sure that char* WILL NOT CHANGE then you can use this: const_cast<char*>(myString.c_str())

If char* may change then you need to copy the string into something else and use that instead. That something else may be std::vector, or new char[], it depends on your needs.

Upvotes: 2

John Dibling
John Dibling

Reputation: 101446

Since you wanted to go from a string to a char* (ie, not a const char*) you can do this BUT BEWARE: there be dragons here:

string foo = "foo";
char* foo_c = &foo[0];

If you try to modify the contents of the string, you're well and truly on your own.

Upvotes: 3

sbi
sbi

Reputation: 224009

Invoke str.c_str() to get a const char*:

const char *pch = str.c_str();

Note that the resulting const char* is only valid until str is changed or destroyed.


However, if you really need a non-const, you probably shouldn't use std::string, as it wasn't designed to allow changing its underlying data behind its back. That said, you can get a pointer to its data by invoking &str[0] or &*str.begin().

The ugliness of this should be considered a feature. In C++98, std::string isn't even required to store its data in a contiguous chunk of memory, so this might explode into your face. I think has changed, but I cannot even remember whether this was for C++03 or the upcoming next version of the standard, C++1x.

If you need to do this, consider using a std::vector<char> instead. You can access its data the same way: &v[0] or &*v.begin().

Upvotes: 15

Bertrand Marron
Bertrand Marron

Reputation: 22210

std::string::c_str() returns a c-string with the same contents as the string object.

std::string str("Hello");
const char* cstr = str.c_str();

Upvotes: 1

aschepler
aschepler

Reputation: 72271

Use the c_str() method on a string object to get a const char* pointer. Warning: The returned pointer is no longer valid if the string object is modified or destroyed.

Upvotes: 3

Related Questions