我在读克莱门斯,本。 21世纪C:来自新学校的C技巧,我被句子“复制结构,混淆数组”所制止,但我并没有很好地理解,这个例子对我来说也不清楚。有人可以解释吗?
示例代码
#include <assert.h>
typedef struct{
int a, b;
double c, d;
int *efg;
} demo_s;
int main(){
demo_s d1 = {.b=1, .c=2, .d=3, .efg=(int[]){4,5,6}};
demo_s d2 = d1;
d1.b=14;
d1.c=41;
d1.efg[0]=7;
assert(d2.a==0);
assert(d2.b==1);
assert(d2.c==2);
assert(d2.d==3);
assert(d2.efg[0]==7);
}
本·克莱门斯21世纪C:新学校的C技巧。 O'Reilly Media。 Kindle版。
#include <assert.h>
int main(){
int abc[] = {0, 1, 2};
int *copy = abc;
copy[0] = 3;
assert(abc[0]==3);
}
本·克莱门斯21世纪C:新学校的C技巧。 O'Reilly Media。 Kindle版。
那作业:
demo_s d2 = d1;
在第一个示例中,实际上复制了该结构的内容。因此,这意味着如果原始结构更改了某些值,则该值将不会反映在副本中(它们不会共享相同的引用),反之亦然。
另一方面,数组的分配:
int *copy = abc;
仅复制名称(引用,指针),而不复制数组的内容。因此,这意味着如果原始数组更改了某些值,则复制的副本(因为它们引用相同的引用)也将反映更改(反之亦然)。
示例中的断言说明了C语言的这一功能。
Note that on first example with struct, the
efg
field is a pointer to an array, and this is also copied but it copies the reference, so this reflects the changes made to field of original struct.