Solved

Is there any padding possible within a unon

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

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Read file descriptor 3 in C 14 104
distributed computing in Python 4 115
Grammars for C C++ and java 1 114
Using ANSI C how to Read a .csv file 10 73
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

863 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now