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

后端 未结 5 1450
时光取名叫无心
时光取名叫无心 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:28

    Put simply, because an array is not a first-class object in C/C++. The only way to assign to an array is to use str(n)cpy or memcpy.

    While an array collapses into a pointer when passed to a function, it is not possible to assign to an array, except at compile-time as initialisation.

提交回复
热议问题