Manan Shah
Manan Shah

Reputation: 377

Assign a string to a fixed length character array

I was searching through SO and I came across this question of assigning fixed length character array to a string. But what I want is the reverse operation, assigning a string to a fixed length character array. For eg if I have

char name[20];
name = "John";

I get a compile time error saying I am assigning char array[4] to char array[20].

How can I get this done ?

Upvotes: 3

Views: 6501

Answers (4)

Bilal Wasim
Bilal Wasim

Reputation: 17

Passing a Constant String wont do the Job as it wont append \0 (escape Characters) to the rest of your array !! strcpy does this automatically for you , all the free spaces are filled with escape characters , thus you get no error !!

Upvotes: 0

Adrian Cornish
Adrian Cornish

Reputation: 23868

Use strncpy

strncpy(name, "John", sizeof(name)-1);

EDIT

As many others pointed out (I was wrong) - strncpy will not always null terminate the string so if you need to use it as a c string then it needs to be explicitly null terminated. It will not overflow it but that may not be all you need

if(sizeof(name)>0)
{
    name[sizeof(name)-1]=0;
}

Upvotes: 3

Leonid Volnitsky
Leonid Volnitsky

Reputation: 9144

char    dst[30];
string  src("hello");
// check here that sizeof(dst) > src.size()
copy(begin(src), end(src),  begin(dst));
dst[src.size()] ='\0';

std::string also has c_str() method. It is expansive - dynamically allocates memory. You can use returned const char* if don't mind const . This c-string will be destructed when src is destructed.

Upvotes: 1

daveh
daveh

Reputation: 3696

Try using strcpy

http://www.cplusplus.com/reference/clibrary/cstring/strcpy/

basically you will want to strcpy(name,"John");

Upvotes: -1

Related Questions