deep copy of struct with Pointer Point in C
c, deep-copy, pointers, struct
Solution
I'm going to assume that the vertices are not shared between objects. That is, they belong to the structure in question.
There are two primary cases to consider:
1. Copying into a new object
2. Copying into an existing object
Copying into the new object is straightforward.
1a. Allocate space for <num_vertex> pointers.
1b. Allocate space for each vertex.
2a. Copy <num_vertex> pointers from source to destination.
2b. Copy <num_vertex> vertices from source to destination.
Copying into an existing object is much the same as copying into a new object except that you have to do the following first.
0a. Loop through each element of <vertex> and free the vertex.
0b. Free the array of vertex pointers.
1. Follow the steps for copying into a new object.
Hope this helps.
Problem
i need your help! I like to copy a struct like this: ``` typedef struct PackageObject_s { long **vertex; // vertices long num_vertex; // count of vertices long objectType; // REAL r; // long bottom[3]; // bounding box bottom vector long top[3]; // bounding box top vector long *start; // REAL coverage; // } PackageObject __attribute__ ((aligned)); ``` I try it like this: ``` static inline void PackageObject_copy(PackageObject *dst, const PackageObject *src) { dst->num_vertex = src->num_vertex; dst->objectType = src->objectType; dst->r = src->r; vec_assign3l(dst->bottom, src->bottom); vec_assign3l(dst->top, src->top); // TODO copy **vertex ??? dst->coverage = src->coverage; dst->coverage = src->coverage; } ``` How can i solve this? Thank you in advance for your help!! UPDATE - my solution for deepcopy of `vertex` - thx for all help: ``` dst->vertex = (long *)malloc(dst->num_vertex * 3 * sizeof(long)); for (long i=0; i < src->num_vertex; i++) { dst->vertex[i] = (long)malloc(3*sizeof(long)); memcpy(dst->vertex[i],src->vertex[i],3 * sizeof(long)); } ```