Sourcerer said:
Hi all.
Can I do this to duplicate the contents of struct a in struct b
struct myStruct a, b, *aptr, *bptr;
aptr = a;
aptr = &a;
bptr = &b;
Do something to initialize contents of structure a
memcpy(bptr, aptr, sizeof(myStruct));
Try these:
b = a;
memcpy(&b, &a, sizeof(struct myStruct));
Or is not not a good idea to assume the memory used
by my structure is contiguous ?
should I instead do it field by field.
I believe that the total space occupied by a structure
is contiguous; however, the compiller is allowed to
add padding between the fields.
When copying one structure to another, memcpy can be
used. But you should have a policy when it comes
to pointer fields:
1. Copy only the pointer and have multiple pointers
to one object.
2. Create a new copy of the target object, thus having
two copies of the target object.
3. Reference counting: multiple pointers to one
object, but the number of references must be zero
before the target object is deleted.
I would copy field by field when copying to or from
a buffer (unsigned char array). Padding bytes may
be copied from one structure to another, but a buffer
may not have padding between the fields.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library