Can someone explain why this works with the pointer:
char * str1;
str1 = \"Hello1\";
str1 = \"new string\";
// but not this
char str2 [] = \"hello\";
str
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.