Assigning strings to arrays of characters

后端 未结 9 1381
小鲜肉
小鲜肉 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 16:03

    When initializing an array, C allows you to fill it with values. So

    char s[100] = "abcd";
    

    is basically the same as

    int s[3] = { 1, 2, 3 };
    

    but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of

    s = "abcd" 
    

    is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array.
    This can and does work if s is a char* - a pointer that can point to anything.

    If you want to copy the string simple use strcpy.

提交回复
热议问题