2

It can be simple but I m new about c++
In char arrays we can let the compiler to count number of characters in the string like

char myarray[]="stringvar";

its ok, but if i change the code as below,the compiler gives error

string myvar = "stringvar";
char myarray[] =myvar;

error: initializer fails to determine size of myarray


Why is that?

Mustafa Ekici
  • 7,263
  • 9
  • 55
  • 75

4 Answers4

4

You can do this:

string myvar = "stringvar";
const char * myarray = myvar.c_str(); //immutable string

In this case, the data whichmyarray points to, lives as long as the lifetime of myvar.

However, if you want a mutable string or, a string which may last longer (or shorter) than the lifetime of myvar, then you've to allocate memory yourself as:

char * myarray = new char[myvar.size()+1]; //mutable string
std::strcpy(myarray, myvar.c_str());

//you've to deallocate the memory yourself as:
delete [] myarray;
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • so in first decleration char myarray[]="stringvar"; compiler understand "stringvar" as pointer? not string class ? am I right? – Mustafa Ekici Feb 05 '12 at 14:31
  • @mekici: Yes, that is not string-class. Also, the type of `"stringvar"` is not pointer either. It is an array of type `char[10]` which may convert into `char*`. – Nawaz Feb 05 '12 at 14:32
1

You cannot assign an std::string object to initialize and create a character array.

You will need to copy the std::string in to the array.

strcpy(myarray,myvar.c_str());
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1
string myvar = "stringvar"
char* myarray = (char*)myvar.c_str();

It should work.

bluish
  • 26,356
  • 27
  • 122
  • 180
xeonarno
  • 426
  • 6
  • 17
1

There is error, because char myarray[] is equivalent to char* myarray. It is just a pointer to char. So you need a compatible initializer there (like char* or const char*). But you are trying to pass an instance of string class, that is not a pointer.

If you wish to assign myarray to a string (make it point to the same location) you may do this

char myarray[] = const_cast<char[]> myvar.c_str();

But in any case, its not good idea, until you definitely know what you're doing.

Andrew D.
  • 1,022
  • 12
  • 26