Mustafa Ekici
Mustafa Ekici

Reputation: 7470

Char array gives error when initializing

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?

Upvotes: 2

Views: 2593

Answers (4)

xeonarno
xeonarno

Reputation: 426

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

It should work.

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361442

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;

Upvotes: 4

Andrew D.
Andrew D.

Reputation: 1022

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.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206526

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());

Upvotes: 1

Related Questions