char *array and char array[]

前端 未结 4 815
心在旅途
心在旅途 2020-12-07 13:25

if I write this

 char *array = \"One good thing about music\";

I actually create an array? I mean it\'s the same like this?



        
4条回答
  •  难免孤独
    2020-12-07 14:04

    No, you're creating an array, but there's a big difference:

    char *string = "Some CONSTANT string";
    printf("%c\n", string[1]);//prints o
    string[1] = 'v';//INVALID!!
    

    The array is created in a read only part of memory, so you can't edit the value through the pointer, whereas:

    char string[] = "Some string";
    

    creates the same, read only, constant string, and copies it to the stack array. That's why:

    string[1] = 'v';
    

    Is valid in the latter case.
    If you write:

    char string[] = {"some", " string"};
    

    the compiler should complain, because you're constructing an array of char arrays (or char pointers), and assigning it to an array of chars. Those types don't match up. Either write:

    char string[] = {'s','o','m', 'e', ' ', 's', 't','r','i','n','g', '\o'};
    //this is a bit silly, because it's the same as char string[] = "some string";
    //or
    char *string[] = {"some", " string"};//array of pointers to CONSTANT strings
    //or
    char string[][10] = {"some", " string"};
    

    Where the last version gives you an array of strings (arrays of chars) that you actually can edit...

提交回复
热议问题