Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 this error?

like image 845
pighead10 Avatar asked Jan 20 '23 19:01

pighead10


2 Answers

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.

like image 140
Charles Keepax Avatar answered Jan 31 '23 11:01

Charles Keepax


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).

like image 42
cnicutar Avatar answered Jan 31 '23 10:01

cnicutar