Solved

Is there any padding possible within a unon

Posted on 2004-04-07
7
211 Views
Last Modified: 2010-05-18
Is there any padding possible within a union like there iare padding fields within a structure.
0
Comment
Question by:VivekGupta22
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
7 Comments
 
LVL 3

Expert Comment

by:idt
ID: 10774905
If you are asking if byte alignment still applies in a union, then the answer is yes
0
 
LVL 10

Expert Comment

by:Sys_Prog
ID: 10774912
0
 
LVL 3

Accepted Solution

by:
idt earned 20 total points
ID: 10774999
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
 
LVL 12

Expert Comment

by:stefan73
ID: 10775525
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

Independent Software Vendors: 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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

718 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question