有人能解释一下为什么指针能起作用吗
char * str1;
str1 = "Hello1";
str1 = "new string";
// but not this
char str2 [] = "hello";
str2 = "four";
// or this
char str3 [];
str3 = "hello";
str3 = "hello";
有人能解释一下为什么指针能起作用吗
char * str1;
str1 = "Hello1";
str1 = "new string";
// but not this
char str2 [] = "hello";
str2 = "four";
// or this
char str3 [];
str3 = "hello";
str3 = "hello";
Why it works with pointers:
当您在C中说char * str1
时,您是在内存中分配一个指针.当您编写str1 = "Hello";
时,您在内存中创建了一个字符串文字,并使指针指向它.当您创建另一个字符串文字"new string"
并将其赋给str1
时,您所做的就是更改指针指向的位置.
Why it doesn't work with arrays:
在str3
的情况下,情况也是如此.您尚未在定义中定义数组的大小,因此它将其大小计算为0.在不调整数组大小的情况下,无法分配任何新内容.