为什么我们不能将新字符串分配给 char 数组,而是分配给指针? [英] Why can´t we assign a new string to an char array, but to a pointer?
问题描述
我试图将一个字符串重新分配给一个预先初始化的数组 a[],但我得到的只是一个错误
i was trying to reassign a string to a pre-initialized array a[], and all i could get was an error
main()
{
char a[] = "Sunstroke";
char *b = "Coldwave";
a = "Coldwave";
b = "Sunstroke";
printf("\n %s %s",a,b);
}
[错误]:从类型 'char *' 分配到类型 'char[10]' 时的类型不兼容.. 我搜索了这个但找不到任何原因.. 我也尝试通过重新声明重新分配它喜欢
[Error]: incompatible types when assigning to type 'char[10]' from type 'char *'.. i searched for this but was unable to find any reason.. i also tried to re-assign it by redeclaration like
char a[] = "Sunstroke";
但是没有用...
但是在指针的情况下,它可以像上面的程序一样..
but in case of a pointer it was possible as in above program..
推荐答案
诸如Coldwave"之类的硬编码字符串文字实际上是 char[]
(字符数组)类型——但它是 未定义行为来修改它们(C99:6.4.5.6).但是请注意,下面的 b
仍然是 char*
(字符指针):
Hard-coded string literals such as "Coldwave" are actually char[]
(char array) types -- but it is undefined behavior to modify them (C99:6.4.5.6). Note that below, however, b
is still a char*
(char pointer):
char *b = "Coldwave";
分配了 char[]
的对象.没关系.但它与此不同:
To which a char[]
has been assigned. That's okay. It is different than this though:
char a[] = "Coldwave";
这是char[]
的初始化.您只能在声明变量时初始化一次,并且初始化是唯一可以通过像这样的赋值来填充数组或其他复合类型(例如结构)的情况.但是,您不能这样做:
Which is an initialization of a char[]
. You can only initialize a variable once, when it is declared, and initialization is the only circumstance in which you can populate an array or other compound type (such as a struct) via assignment like this. You could not do this, however:
char c[] = a;
因为当在赋值语句的右侧使用时,数组变量的作用就像指向它们所代表的数组的指针一样,这就是 char *b = a
起作用的原因.
Because when used on the right hand side of an assignment, array variables function as pointers to the array they represent, which is why char *b = a
works.
所以你不能用上面的变量做到这一点的原因:
So the reason you can't do this with the variables from above:
a = b;
// or
a = "Sunstroke";
是因为这会将 char*
分配给 char[]
—— 不好;你只能反过来做.
Is because that would be assigning a char*
to a char[]
-- no good; you can only do it the other way around.
这篇关于为什么我们不能将新字符串分配给 char 数组,而是分配给指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!