Search code examples
c++cmemcpy

Copy structure to a different structure


I was wondering if there was an elegant way to copy a structure to a different structure, where the second structure is essentially the same as the original one, except without the last field(s).

For example,

struct A {
    int a;
    int b;
    int c;
};
struct B {
    int a;
};

struct A v1;
struct B v2;

Would,

memcpy(&v2, &v1, sizeof(v2));

Achieve the functionality I wish? Where v2 has the "a" value that was originally found in v1?

Thank you


Solution

  • If instead of copying all bytes in A, you only copy the number of bytes that B expects, you will achieve your desired result:

    memcpy(&v2, &v1, sizeof(v2)); // remember that the first argument is the destination
    

    However, this is not good coding style. With this minimal code example, it is hard to tell, but you would probably want A to inherit from B so that you can convert the two without having to physically copy memory.

    Otherwise, this would be easier and cleaner:

    b2.a = v1.a;