0

Hi guys I want to add this long variable l_cliend_id without corrupting the data in this union

union _V2_INPUT
{
     struct _V2_HEADER            header;
     struct _IN_DETAIL            detail;
     struct _V2_TRAILER           trailer;
};

How do add it cleanly without corrupting the exiting data in the union buffer?

user3419585
  • 13
  • 1
  • 1
  • 7
  • This is unclear to me. A union is not a buffer and there is no "existing data" in it which you can corrupt. Maybe you're concerned about offsets of the fields in the three structures? – Aaron Digulla May 06 '14 at 08:45
  • You can add anything to a union without "corrupting" the data, as long at the size of the new member you add is equal or smaller in size than the existing members. – Some programmer dude May 06 '14 at 08:45
  • Cool thanks that should work :-) sorry for the silly question – user3419585 May 06 '14 at 08:45
  • Yes I'm worried about the offsets of the fields in the three structures. How do I add the new field without changing the offsets of the fields in the three structures – user3419585 May 06 '14 at 08:47
  • You *do* know what a `union` is? All members of a `union` share the same memory. If you add a new member no offsets of the old members will change, as there is no offset between members. And as there is no offset, it doesn't matter where in the `union` you add the new member. – Some programmer dude May 06 '14 at 08:52
  • If the `sizeof(union _V2_INPUT)` before and after adding `long` is the same, there is nothing you should worry about. –  May 06 '14 at 08:57
  • If I add the long variable to structure _IN_DETAIL would the length of structure _V2_TRAILER change? – user3419585 May 06 '14 at 11:14

1 Answers1

1

It's simply:

union _V2_INPUT
{
     struct _V2_HEADER            header;
     struct _IN_DETAIL            detail;
     struct _V2_TRAILER           trailer;
     long                         l_cliend_id;
};

That allows you to store one of the three structures or just the l_cliend_id.

Unlike struct, union puts the elements at the same offset, so you have &u->l_cliend_id == &u->header == &u->detail == &u->trailer. This means that you can put only one of the four into the allocated memory. If you put data into, say, header and l_cliend_id, the second assignment will corrupt the header.

Don't forget to compile all the code which uses the new union!

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820