简体   繁体   中英

How can I transfer string to char* (not const char*)

I wanna do something like:

string result;
char* a[100];
a[0]=result;

it seems that result.c_str() has to be const char*. Is there any way to do this?

You can take the address of the first character in the string.

a[0] = &result[0];

This is guaranteed to work in C++11. (The internal string representation must be contiguous and null-terminated like a C-style string)

In C++03 these guarantees do not exist, but all common implementations will work.

string result;
char a[100] = {0};
strncpy(a, result.c_str(), sizeof(a) - 1);

There is a member function (method) called "copy" to have this done.

but you need create the buffer first.

like this

string result;
char* a[100];
a[0] = new char[result.length() + 1];
result.copy(a[0], result.length(), 0);
a[0][result.length()] = '\0';

(references: http://www.cplusplus.com/reference/string/basic_string/copy/ )

by the way, I wonder if you means

string result;
char a[100];

You can do:

char a[100];
::strncpy(a, result.c_str(), 100);

Be careful of null termination.

The old fashioned way:

#include <string.h>

a[0] = strdup(result.c_str());  // allocates memory for a new string and copies it over
[...]
free(a[0]);  // don't forget this or you leak memory!

If you really, truly can't avoid doing this, you shouldn't throw away all that C++ offers, and descend to using raw arrays and horrible functions like strncpy .

One reasonable possibility would be to copy the data from the string to a vector:

char const *temp = result.c_str();
std::vector<char> a(temp, temp+result.size()+1);

You can usually leave the data in the string though -- if you need a non-const pointer to the string's data, you can use &result[0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM