Assigning strings to arrays of characters

后端 未结 9 1379
小鲜肉
小鲜肉 2020-11-22 15:03

I am a little surprised by the following.

Example 1:

char s[100] = \"abcd\"; // declare and initialize - WORKS

Example 2:



        
9条回答
  •  臣服心动
    2020-11-22 15:40

    1    char s[100];
    2    s = "hello";
    

    In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did. At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy() or some kind of loop to assign each element of the array.

提交回复
热议问题