Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, why can't I assign a string to a char array after it's declared?

This has been bugging me for a while.

struct person {
       char name[15];
       int age;
};
struct person me;
me.name = "nikol";

when I compile I get this error:

error: incompatible types when assigning to type ‘char[15]’ from type ‘char *’

am I missing something obvious here?

like image 329
Kok Nikol Avatar asked Nov 01 '14 21:11

Kok Nikol


People also ask

Can I assign a string to a char array in C?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0').

Can we store string in char array?

You can store a string in a char array of length 1, but it has to be empty: The terminating null character is the only thing that can be stored.

Can we assign string to char?

We can directly assign the address of 1st character of the string to a pointer to char. This should be the preferred method unless your logic needs a copy of the string.


2 Answers

Arrays are second-class citizens in C, they do not support assignment.

char x[] = "This is initialization, not assignment, thus ok.";

This does not work:

x = "Compilation-error here, tried to assign to an array.";

Use library-functions or manually copy every element for itself:

#include <string.h>
strcpy(x, "The library-solution to string-assignment.");
like image 142
Deduplicator Avatar answered Oct 13 '22 15:10

Deduplicator


me.name = "nikol"; is wrong !! you need to use strcpy()

when you do x = "Some String", actually you are putting the starting address of the static string "Some String" into variable x. In your case, name is a static array, and you cannot change the address. What you need, is to copy your string to the already allocated array name. For that, use strcpy().

like image 31
Sourav Ghosh Avatar answered Oct 13 '22 17:10

Sourav Ghosh