可能重複:
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