Solved

Is there any padding possible within a unon

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

809 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