Assigning strings to arrays of characters

后端 未结 9 1377
小鲜肉
小鲜肉 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:55

    Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 16:04

    I know that this has already been answered, but I wanted to share an answer that I gave to someone who asked a very similar question on a C/C++ Facebook group.


    Arrays don't have assignment operator functions*. This means that you cannot simply assign a char array to a string literal. Why? Because the array itself doesn't have any assignment operator. (*It's a const pointer which can't be changed.)

    arrays are simply an area of contiguous allocated memory and the name of the array is actually a pointer to the first element of the array. (Quote from https://www.quora.com/Can-we-copy-an-array-using-an-assignment-operator)

    To copy a string literal (such as "Hello world" or "abcd") to your char array, you must manually copy all char elements of the string literal onto the array.

    char s[100]; This will initialize an empty array of length 100.

    Now to copy your string literal onto this array, use strcpy

    strcpy(s, "abcd"); This will copy the contents from the string literal "abcd" and copy it to the s[100] array.

    Here's a great example of what it's doing:

    int i = 0; //start at 0
    do {
        s[i] = ("Hello World")[i]; //assign s[i] to the string literal index i
    } while(s[i++]); //continue the loop until the last char is null
    

    You should obviously use strcpy instead of this custom string literal copier, but it's a good example that explains how strcpy fundamentally works.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题