2012-01-28 39 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