Setting a char array with c_str()?
char el[3] = myvector[1].c_str();
myvector[i]
is a string with three letters in. Why does t开发者_JAVA技巧his error?
It returns type char* which is a pointer to a string. You can't assign this directly to an array like that, as that array already has memory assigned to it. Try:
const char* el = myvector[1].c_str();
But very careful if the string itself is destroyed or changed as the pointer will no longer be valid.
Because a const char *
is not a valid initializer for an array. What's more, I believe c_str
returns a pointer to internal memory so it's not safe to store.
You probably want to copy the value in some way (memcpy
or std::copy
or something else).
In addition to what others have said, keep in mind that a string with a length of three characters requires four bytes when converted to a c_str. This is because an extra byte has to be reserved for the null at the end of the string.
Arrays in C++ must know their size, and be provided with initialisers, at compile-time. The value returned by c_str() is only known at run-time. If e1 were a std::string, as it probably should be, there would be no problem. If it must be a char[], then use strcpy to populate it.
char el[3];
strcpy( e1, myvector[1].c_str() );
This assumes that the string myvector[1] contains at most two characters.
Just create a copy of the string. Then, if you ever need to access it as a char*, just do so.
string el = myvector[1];
cout << &el[0] << endl;
Make the string const if you don't need to modify it. Use c_str() on 'el' instead if you want.
Or, just access it right from the vector with:
cout << &myvector[1][0] << endl;
if possible for your situation.
精彩评论