可能重复:
Why does C++ support memberwise assignment of arrays within structs, but not generally?分配阵列和struct用C
在C语言中,struct
可以通过立即指派但array
不能被复制。
int a[2] = {1, 2};
int a2[2] = a; /*illegal*/
int *p = a; /*assigned by reference*/
struct S {int i; int j;};
struct S s = {1, 2};
struct S s2 = s; /*assigned by value*/
什么设计优势在C语言来区分的array
和struct
分配?
@EDIT
事实上,我们通常想到调用C函数像许多其他语言时,按值传递的,但如果参数的array
,它有效地通过引用传递。
struct S {int i; int j;};
void pass_by_value(struct S s);
struct S s2 = {1, 2};
pass_by_value(s2); /* s2 is copied to s */
void pass_by_ref(int a[]);
int a2[] = {1, 2};
pass_by_ref(a2); /* a2 is referenced to a */
有一个语法糖为array
普遍在C编程:
array_var == &array_var
如果我们希望有一个新的语言功能,array
可以像struct
通过立即指派,遗留代码被复制那么肯定会破碎。这是C中有一个可克隆array
的主要障碍之一吗?
从技术上讲,您显示的这些行都不是_assignments_,它们是_initialization_。你不能'int a [2]; a = {1,2};'虽然'int a [2] = {1,2};'是合法的,并且'struct's不能做'struct S {int i; int j; } s; s = {1,2};'但是你可以在C99中做's =(struct S){1,2};'。 – 2012-01-28 21:33:30