2012-01-28 40 views
1

可能重複:
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語言來區分的arraystruct分配?

@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的主要障礙之一嗎?

+1

從技術上講,您顯示的這些行都不是_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

回答

1

In pre-K & R C struct對象也不可轉讓。當這種情況發生變化時,也考慮了數組,但是人們注意到C標準需要進行許多更改以適應數組。

0

你甚至可以這樣做:

struct S { 
    int a[2]; 
}; 

,輕鬆地將它們分配。所以如果你把它們包裝在一個結構中,數組可以被間接地分配。

+0

爲什麼downvote?這是100%正確的。 – 2012-01-29 02:57:39