Solved

Is there any padding possible within a unon

Posted on 2004-04-07
7
208 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
  • 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

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
how to find a data that is pure string   or not in vb.net ? 9 108
Picking random number 8 177
Grammars for C C++ and java 1 122
Problem to save 10 165
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 opening and writing to files 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.

773 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