Search code examples
carraysstringinitializationassign

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?


Solution

  • 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.");