Setting char array with c_str ()?

char el[3] = myvector[1].c_str();

myvector[i]is a string with three letters. Why is this a mistake?

+3
source share
5 answers

It returns a char * type, which is a pointer to a string. You cannot assign it directly to an array, since this array already has memory assigned to it. Try:

const char* el = myvector[1].c_str();

But be very careful if the string itself is destroyed or changed, because the pointer will no longer be valid.

+5
source

In addition to what others have said, keep in mind that a string with a length of three characters requires four bytes when converting to c_str. This is because the extra byte must be reserved for zero at the end of the line.

+2
source

const char * . , , c_str , .

, (memcpy std::copy - ).

+1

++ . , c_str(), . e1 std::string, , . char [], strcpy .

char el[3];
strcpy( e1, myvector[1].c_str() );

, myvector [1] .

0

. , - char *, .

string el = myvector[1];
cout << &el[0] << endl;

const, . c_str() 'el', .

:

cout << &myvector[1][0] << endl;

if possible for your situation.

0
source

All Articles