当我制作结构的浅拷贝时,灵活的数组成员不会被复制 [英] Flexible array member not getting copied when I make a shallow copy of a struct

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

问题描述

我以如下方式制作了一个结构体的浅拷贝:

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 的第一个元素时,它为空.但是如果我检查原始结构中灵活数组成员的第一个元素,它会成功打印出指针.原始结构的所有其他组件都像名称和链表一样被复制.只有灵活的数组成员没有被复制.有谁知道我做错了什么?

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;.

既然你do显然知道整个结构的大小,为了malloc它,只需使用memcpy复制那么多字节.或者,如果您担心这在某种程度上不可移植(老实说我不确定),请执行分配,然后使用循环从 one->friends
oneCopy->朋友.

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天全站免登陆