string literal in c

前端 未结 6 975
刺人心
刺人心 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:02

    As other answers have already pointed out, you can only initialise a character array with a string literal, you cannot assign a string literal to a character array. However, structs (even those that contain character arrays) are another kettle of fish.

    I would not recommend doing this in an actual program, but this demonstrates that although arrays types cannot be assigned to, structs containing array types can be.

    typedef struct
    {
        char value[100];
    } string;
    
    int main()
    {
        string a = {"hello"};
        a = (string){"another string!"}; // overwrite value with a new string
        puts(a.value);
    
        string b = {"a NEW string"};
        b = a; // override with the value of another "string" struct
        puts(b.value); // prints "another string!" again
    }
    

    So, in your original example, the following code should compile fine:

    typedef struct{
        char a[6];
    } point;
    
    int main()
    {
       point p;
    
       // note that only 5 characters + 1 for '\0' will fit in a char[6] array.
       p = (point){"onetw"};
    }
    

提交回复
热议问题