• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 215
  • Last Modified:

Is there any padding possible within a unon

Is there any padding possible within a union like there iare padding fields within a structure.
0
VivekGupta22
Asked:
VivekGupta22
  • 2
1 Solution
 
idtCommented:
If you are asking if byte alignment still applies in a union, then the answer is yes
0
 
Sys_ProgCommented:
0
 
idtCommented:
consider the following

struct mStruct {
  char c;
  int i;
}

union myUnion {
  char s[2];
  myStruct t;
}

int i will NOT be aligned with s[1], but will be at s+2.
memory offset
01234567890
c.ii
ss

memory item '.' is unused
Daniel
0
 
stefan73Commented:
Hi VivekGupta22,
> Is there any padding possible within a union

Yes, you can add a "dummy" array:

union my_union {
  int real_data_a;
  long double real_data_b;
  char dummy_padding[16];
};

This will make sure that the union is padded to 16 bytes, regardless of how long double is implemented on your machine (i.e., 80 bit on Intel, 128 on SPARC).


Cheers,
Stefan
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now