I have the following two structures. I need to copy d, e, f from source to destination using memcpy and offsetof. How can I do this?
struct source
{
int a;
int b;
int c;
int d;
int e;
int f;
};
struct destination
{
int d;
int e;
int f;
};
Generally, You cannot reliably do it using
memcpy, because the compiler is allowed to pad the two structures differently. So the safest way of performing a partial copy would be to assign the three fields individually.However, since the compiler inserts padding only between members with different alignment requirements, in your specific case you can use
memcpylike this:The offset of
destination‘sdis guaranteed to be zero because it is the initial member of the structure. Since membersd,e, andfhave identical alignment requirements, the padding, if any, will go after them in thestruct destination, and before or after them in thestruct source.Cast to
char*is required because the offset is expressed in bytes.The expression
is the length of the run between
dandf, inclusive. Note that usingsizeof(struct destination)is not safe, because it may have padding at the end which is not present instruct source, causing a read past the allocated memory.