I have a pointer to a structure and I need to implement a method that will copy all of the memory contents of a structure. Generally speaking I need to perform a deep copy of a structure.
Here's the structure:
typedef struct {
Size2f spriteSize;
Vertex2f *vertices;
GLubyte *vertex_indices;
} tSprite;
And here's the method I've implemented that should copy the structure:
tSprite* copySprite(const tSprite *copyFromMe)
{
tSprite *pSpriteToReturn = (tSprite*)malloc( sizeof(*copyFromMe) );
memcpy(pSpriteToReturn, copyFromMe, sizeof(*copyFromMe) );
return pSpriteToReturn;
}
The problem is that I'm not sure that arrays "vertices" and "vertex_indices" are going to be copied properly. What is going to be copied in this way? Address of the array or the array itself?
Should I copy the arrays after copying the structure? Or is it enough just to copy the structure?
Something like this:
...
pSpriteToReturn->vertices = (Vector2f*)malloc( sizeof(arraysize) );
memcpy(pSpriteToReturn->vertices, copyFromMe->vertices, sizeof(arraysize) );
...
Thank you in advance.
We can also use assignment operator to make copy of struct. A lot of people don't even realize that they can copy a struct this way because one can't do same it with an array. Similarly one can return struct from a function and assign it but not array. The compiler do all the copying stuff behind the scene for us.
In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable.
No you cannot. C does not support the concept of inheritance.
As a rule of thumb, don’t ever use memcpy
in C++ in normal code (it might crop up in very low-level code, e.g. in allocators)1). Instead, create a suitable copy constructor and overload operator =
(the assignment operator) to match it (and a destructor – rule of three: “if you implement either of copy constructor, operator =
and destructor, you must implement all three).
If you do not implement your own versions of the copy constructor an the assignment operator, C++ will create default versions for you. These versions will implement a shallow copy (much like what memcpy
would do), i.e. in your case the array contents would not be copied – only the pointers.
1) Incidentally, the same goes for malloc
and free
. Don’t use them, instead use new
/new[]
and delete
/delete[]
.
This partially depends on your requirements. If you don't copy the arrays, both structures will be pointing to the same array, which may or may not be a problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With