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

myvector[i] is a string with three letters in. Why does this error?

pighead10
  • 4,155
  • 10
  • 34
  • 52

5 Answers5

5

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.

Charles Keepax
  • 2,392
  • 1
  • 18
  • 19
  • 2
    Not only if the string is destroyed - the pointer will also be invalidated if the string is changed. –  May 07 '11 at 08:29
2

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

cnicutar
  • 178,505
  • 25
  • 365
  • 392
2

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.

Kaivosukeltaja
  • 15,541
  • 4
  • 40
  • 70
0

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.

  • `std::copy(myvector[1].begin(), myvector[1].begin() + 3, e1)` doesn't require any assumption! – Nawaz May 07 '11 at 08:34
  • @Nawaz It assumes the OP does not want the result to be null-terminated. –  May 07 '11 at 08:36
0

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.

Shadow2531
  • 11,980
  • 5
  • 35
  • 48