#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    17
    Rep Power
    0

    How to copy the data from a struct/union variable


    Code:
    struct A
     {
        union 
        {
          struct B
          {}b;
          struct C
          {}c;
          struct D
          {}d;
        }e;
     
       struct F
        {}f;
        ....
     }a;
     A b;
    I want to copy the data of a to b, or just the union part of a to b. There two ways:
    (1) b = a; b.e = a.e;
    (2) memcpy(&b,&a, sizeof(a)); memcpy(&b.e,&a.e, sizeof(a.e));
    I am confused and not sure which method is correct.
    I hope someone can explain.
    Thanks!
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,417
    Rep Power
    1871
    > (1) b = a; b.e = a.e;
    Since this actually works, I'd go with this approach.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo