Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy a struct to another

I have a struct which contains strings and pointer within. Is there any library functions available to do a deep copy of the struct into another. I don't want to do a field by field copy since the struct I'm having is quite large.

Does glib have any function that does the trick?

like image 927
broun Avatar asked Dec 27 '22 05:12

broun


2 Answers

No. A general-purpose function would have no way to know the structure of your struct (i.e. the information that's only available at compile time). And even if it did, how it would know what constitutes a "deep copy" in all circumstances?

like image 145
Oliver Charlesworth Avatar answered Jan 15 '23 16:01

Oliver Charlesworth


You can use memcpy or memmove to copy the entire contents of the struct itself. However, as C has no introspection, copying pointed-to objects can't be done by a general purpose function.

Edited to add: As several commenters note, you can just assign structures to other structures in the C dialects in use for the last couple of decades, memcpy is not needed any longer.

like image 39
Perry Avatar answered Jan 15 '23 14:01

Perry