Why can a string be assigned to a char* pointer, but not to a char[] array?

后端 未结 5 1464
时光取名叫无心
时光取名叫无心 2020-12-07 07:38

Can someone explain why this works with the pointer:

char * str1;

str1 = \"Hello1\";

str1 = \"new string\";

// but not this
char str2 [] = \"hello\";
str         


        
5条回答
  •  一个人的身影
    2020-12-07 08:05

    An array and a pointer are different things, that's why. You can assign to a pointer, but you can't assign to an array. A special exception is made for initialization of char arrays with string literals.

    char a[] = "Hello"; //initialize a char array with string literal. Special case, OK
    char* p = "Hello"; //initializa a pointer with an array(which gets converted to pointer)
    p = "My";   //assign pointer to point to another value. OK
    a = "My";   //error, arrays cannot be assigned to. Use `strcpy`
    

    String literals (such as "Hello") have type char[N] where N is number of characters (including the terminating '\0'). An array can be converted to a pointer to its first element, but arrays and pointers are not the same thing, whatever some bad books or teachers may say.

提交回复
热议问题