0

Okay, so I have a struct of structs of structs of stru... Is there anyway to copy the entire struct with all the data into a new one without having to allocate a whole other series of structs?

atb
  • 943
  • 4
  • 14
  • 30

1 Answers1

3

Yes, just assign:

MyStruct a;
MyStruct b;

...

a = b;

This performs a shallow copy; if any of the structures contain pointers, then it's only the pointer is copied, not the stuff being pointed to. If you need a deep copy, you will have to write your own routine.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • +1. However, depending on your environment a simple assignment may not be sufficient. Some compilers will emit a literal call to `memcpy`, so if that symbol isn't defined in your environment (or has strange semantics), you might find yourself in trouble. – Carl Norum Mar 16 '12 at 00:41
  • @CarlNorum: That would be extremely annoying, given that the above is well-defined C89... – Oliver Charlesworth Mar 16 '12 at 00:42
  • It is in fact extremely annoying, but unfortunately real. – Carl Norum Mar 16 '12 at 00:43
  • @CarlNorum: Undoubtedly. Can you suggest a compiler that does this? – Oliver Charlesworth Mar 16 '12 at 00:46
  • GCC, clang, and Visual Studio all do it. In fact, said behaviour cannot even be avoided in some versions. – Carl Norum Mar 16 '12 at 00:47
  • Here's a [Stack Overflow question](http://stackoverflow.com/questions/6410595/getting-gcc-to-compile-without-inserting-call-to-memcpy) that talks about it, and a [link to the GCC documentation](http://gcc.gnu.org/onlinedocs/gcc/Standards.html) describing the required functions - specifically `memcpy`, `memmove`, `memset` and `memcmp`. – Carl Norum Mar 16 '12 at 00:52