Why it works with pointers:
When you say char * str1
in C, you are allocating a pointer in the memory. When you write str1 = "Hello";
, you are creating a string literal in memory and making the pointer point to it. When you create another string literal "new string"
and assign it to str1
, all you are doing is changing where the pointer points.
Why it doesn't work with arrays:
When you say char str2 [] = "Hello"
, you are creating a string literal and putting it in the array during its definition. It is ok to not give a size, as the array calculates it and appends a ''
to it. You cannot reassign anything to that array without resizing it. That is why str2 = "four"
will not work.
In case of str3
, it is the same case. You haven't defined the size of the array in the definition, so it calculated its size to be 0. You cannot assign anything new without resizing the array.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…