Re: Copying a struct to a larger struct?
- From: Michael Mair <Michael.Mair@xxxxxxxxxxxxxxx>
- Date: Wed, 27 Jul 2005 23:15:51 +0200
hermes_917@xxxxxxxxx wrote:
I want to use memcpy to copy the contents of one struct to another which is a superset of the original struct (the second struct has extra members at the end). I wrote a small program to test this, and it seems to work fine, but are there any cases where doing something like this could cause any problems?
Here's the small program I wrote to test this:
#include <stdio.h>
int main() { struct simplestruct { int i; char str[8]; };
struct extendedstruct { int i; char str[8]; int j; };
struct simplestruct foostruct; struct extendedstruct barstruct;
/* Populate the members of the simplestruct instance */ foostruct.i=7; strcpy(foostruct.str, "Test");
/* Copy the contents of the simplestruct instance to the extendedstruct instance */ memcpy(&barstruct, &foostruct, sizeof(foostruct));
/* Populate remaining member of the extendedstruct instance */ barstruct.j=13;
/* Print values of members of the extendedstruct instance */ printf("i\t%d\nstr\t%s\nj\t%d\n", barstruct.i, barstruct.str, barstruct.j); }
Thanks in advance for any advice.
It is possible that sizeof foostruct == sizeof barstruct; take another example:
struct simplestruct
{
int i;
char str[7];
}; struct extendedstruct
{
int i;
char str[7];
unsigned char j;
};On typical implementations with 8bit char and 32bit or 16bit int and
minimal padding, it is now probable that sizeof foostruct == sizeof barstruct, so your padding in simplestruct overwrites your useful
information in extendedstruct.
So, either you memcpy() (offsetof(struct simplestruct, str) + sizeof foostruct.str) bytes (the offsetof macro comes from <stddef.h>) or
you follow the hint given in another reply, namely
struct extendedstruct
{
struct simplestruct mySimple;
unsigned char j;
}
Then, you do not even need memcpy():
barstruct.mySimple = foostruct;
suffices.
(In addition, you can abuse the address of barstruct as a
struct simplestruct*, if necessary -- but I have not said that ;-))
Cheers Michael -- E-Mail: Mine is an /at/ gmx /dot/ de address. .
- References:
- Copying a struct to a larger struct?
- From: hermes_917@xxxxxxxxx
- Copying a struct to a larger struct?
- Prev by Date: Re: Hints on how to migrate from C++ to C
- Next by Date: Re: Hints on how to migrate from C++ to C
- Previous by thread: Re: Copying a struct to a larger struct?
- Next by thread: Re: Copying a struct to a larger struct?
- Index(es):
Relevant Pages
|