当我对结构进行浅拷贝时,灵活数组成员没有被复制 [英] Flexible array member not getting copied when I make a shallow copy of a struct

查看:128
本文介绍了当我对结构进行浅拷贝时,灵活数组成员没有被复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已通过以下方式对我拥有的结构进行了浅拷贝:

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?

推荐答案

有人知道我在做什么错吗?

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):

分配*s1 = *s2仅复制成员n [即结构的一部分,不是灵活的数组];如果任何数组元素在结构的前sizeof (struct s)个字节之内,则可能会复制它们或用不确定的值简单地覆盖它们.

The assignment *s1 = *s2 only copies the member n [i.e. the part of the struct that isn't a flexible array]; if any of the array elements are within the first sizeof (struct s) bytes of the structure, they might be copied or simply overwritten with indeterminate values.

基本上,当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:

特别是,结构的大小就像省略了柔性阵列构件,只是它的尾随填充量可能比省略所暗示的要多.

In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

这就是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 to
oneCopy->friends.

这篇关于当我对结构进行浅拷贝时,灵活数组成员没有被复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆