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
}
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?
In your code snippet the structure declaration is wrong. I think you mean a typedef of a structure instead of declaring an object of the structure.
For example
This call of malloc is also wrong
There should be
Here is a demonstrative program that shows how the function can be written
Its output is
Take into account that it is desirable that the structure also contains a data member that will store the number of elements in the flexible array.:)
Trying to use assignment to copy a struct with a flexible array member. From the standard (6.7.2.1):
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:
That's what
sizeof(*one)
is, and that's the size of what gets copied when you do*oneCopy = *one;
.Since you do apparently know the size of the entire structure, in order to
malloc
it, just copy that many bytes usingmemcpy
. 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 fromone->friends
tooneCopy->friends
.