String pointer and array of chars in c

后端 未结 5 2068
南方客
南方客 2021-02-06 02:19

I just start learning C and found some confusion about the string pointer and string(array of char). Can anyone help me to clear my head a bit?

// source code
ch         


        
5条回答
  •  粉色の甜心
    2021-02-06 02:42

    When you say

    char *name3 = "Apple";
    

    you are declaring name3 to point to the static string "Apple". If you're familiar with higher-level languages, you can think of this as immutable (I'm going to explain it in this context because it sounds like you've programmed before; for the technical rationale, check the C standard).

    When you say

    char name4[10];
    name4 = "Apple";
    

    you get an error because you first declare an array of 10 chars (in other words, you are 'pointing' to the start of a 10-byte section of mutable memory), and then attempt to assign the immutable value "Apple" to this array. In the latter case, the actual data allocation occurs in some read-only segment of memory.

    This means that the types do not match:

    error: incompatible types when assigning to type 'char[10]' from type 'char *'
    

    If you want name4 to have the value "Apple", use strcpy:

    strcpy(name4, "Apple");
    

    If you want name4 to have the initial value "Apple", you can do that as well:

    char name4[10] = "Apple"; // shorthand for {'A', 'p', 'p', 'l', 'e', '\0'}
    

    The reason that this works, whereas your previous example does not, is because "Apple" is a valid array initialiser for a char[]. In other words, you are creating a 10-byte char array, and setting its initial value to "Apple" (with 0s in the remaining places).

    This might make more sense if you think of an int array:

    int array[3] = {1, 2, 3}; // initialise array
    

    Probably the easiest colloquial explanation I can think of is that an array is a collection of buckets for things, whereas the static string "Apple" is a single thing 'over there'.

    strcpy(name4, "Apple") works because it copies each of the things (characters) in "Apple" into name4 one by one.

    However, it doesn't make sense to say, 'this collection of buckets is equal to that thing over there'. It only makes sense to 'fill' the buckets with values.

提交回复
热议问题