string literal in c

前端 未结 6 996
刺人心
刺人心 2021-01-05 09:12

Why is the following code illegal?

typedef struct{
   char a[6];
} point;

int main()
{
   point p;
   p.a = \"onetwo\";
}

Does it have any

6条回答
  •  佛祖请我去吃肉
    2021-01-05 10:16

    You can never assign to arrays after they've been created; this is equally illegal:

    int foo[4];
    int bar[4];
    foo = bar;
    

    You need to use pointers, or assign to an index of the array; this is legal:

    p.a[0] = 'o';
    

    If you want to leave it an array in the struct, you can use a function like strcpy:

    strncpy(p.a, "onetwo", 6);
    

    (note that the char array needs to be big enough to hold the nul-terminator too, so you probably want to make it char a[7] and change the last argument to strncpy to 7)

提交回复
热议问题