Deep copy structure with pointer point in C

I need your help!

I like to copy the structure as follows:

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 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 is my solution for deepcopy vertex- thanks for all the 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)); 
}
+5
source share
3 answers

I am going to assume that the vertices are not shared between objects. That is, they belong to the structure under consideration.

There are two main cases:

1. Copying into a new object
2. Copying into an existing object

Copying to a new object is simple.

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 to an existing object is much the same as copying to a new object, except that you must do the following.

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.

+2
source

Original answer:

, 3 longs (x, y, z):

dst->vertex = (long **)malloc(dst->num_vertex * 3 * sizeof(long);
memcpy(dst,src,dst->num_vertex * 3 * sizeof(long));  

, , , , ,

typedef struct vertextag { 
  long x;
  long y;
  long z;
} vertex_type;

:   dst- > vertex = (vertex_type *) malloc (dst- > num_vertex * sizeof (vertex_type);   memcpy (dst, src, dst- > num_vertex * sizeof (vertex_type));

+2

, , , . , ( , ). , , .

, , .

dst->vertex = src->vertex;

If each object has its own vertices (therefore, they can be changed separately for the copied object), then you need to select and copy the array and the place where the pointer is stored, and set the pointer to this place in the copy-object folder.

long* vertexCopy = malloc(howmanybytes);
memcpy(vertexCopy, *src->vertex, howmanybytes);
long** holder = malloc(sizeof(void*));
holder[0] = vertexCopy;
dst->vertex = holder;
+1
source

All Articles