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

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

    The case with pointers It works because when you are assigning like str1="Hello" , You are actually creating a string literal named hello allocating it somewhere in the memory , and assigning the address of first character of the literal to the pointer , and as the pointer is not constant you can assign it again with different addresses. And one more important point to note is that the string literal created are in read only memory.

    The case with character array You can assign it a string literal while initialisation as that is supported by the language . And dont confuse assignment with initialisation. While assignment , since its an character array you have to change value character by character ,You are trying to address the first address of the string literal to the first character of the array ( the name of the array return the address of first element of the array).And this clearly is not right as the first element is not pointer , it cant store address.

提交回复
热议问题