问题描述
我试图重新分配字符串到pre-初始化数组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 [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 it didnt worked...
,但在一个指针的情况下,有可能在上述程序..
but in case of a pointer it was possible as in above program..
推荐答案
硬codeD字符串,如Coldwave实际上的char []
(CHAR数组)类型 - 但它的未定义行为的修改它们(的: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;
由于在赋值的右侧使用时,数组变量指向他们重新present数组,这就是功能为什么的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.
这篇关于为什么不能,我们一个新的字符串赋值给一个数组,而是一个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!