问题描述
我已通过以下方式对我拥有的结构进行了浅拷贝:
I have made a shallow copy a struct I have in the following manner:
struct Student{
char *name;
int age;
Courses *list; //First course (node)
Student *friends[]; //Flexible array member stores other student pointers
}Student;
void shallowCopy(const Student *one){
Student *oneCopy = malloc(sizeof(one) + 20*sizeof(Student*));
*oneCopy = *one; <--------------- ERROR POINTS TO THIS LINE
}
当我检查柔性数组成员的第一个元素oneCopy
时,它为null.但是,如果我在原始结构中检查了弹性数组成员的第一个元素,它将成功打印出指针.将复制原始结构的所有其他组件,例如名称和链接列表.只是不会复制灵活数组成员.有人知道我在做什么错吗?
When I check the first element of the flexible array member it oneCopy
, it is null. But if I check the first element of the flexible array member in the original struct it prints out the pointer successfully. All the other components of the original struct are copied over like the name and the linked list. It is only the flexible array member that is not getting copied. Does anyone know what I am doing wrong?
推荐答案
试图使用赋值来复制具有灵活数组成员的结构.根据标准(6.7.2.1):
Trying to use assignment to copy a struct with a flexible array member. From the standard (6.7.2.1):
基本上,当C编译器看到具有灵活数组成员的结构时,它不知道其实际大小,因此将其视为足以容纳其他成员的结构,并可能加上 其他:
Basically, when the C compiler sees a struct with a flexible array member, it doesn't know how big it really is, so it treats it as being big enough to hold the other members, plus possibly some more:
这就是sizeof(*one)
的含义,而那是执行*oneCopy = *one;
时要复制的内容的大小.
That's what sizeof(*one)
is, and that's the size of what gets copied when you do *oneCopy = *one;
.
由于您做显然知道整个结构的大小,为了进行malloc
处理,只需使用memcpy
复制那么多字节.或者,如果您担心这种方式难以携带(坦率地说,我不确定),请执行赋值操作,然后 then 使用循环将每个元素从one->friends
复制到oneCopy->friends
.
Since you do apparently know the size of the entire structure, in order to malloc
it, just copy that many bytes using memcpy
. Or if you're concerned that that's somehow unportable (honestly I'm not sure), do the assignment, then use a loop to copy each element from one->friends
tooneCopy->friends
.
这篇关于当我对结构进行浅拷贝时,灵活数组成员没有被复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!