Adithya
Adithya

Reputation: 43

Generate padding bytes for a structure by nesting it in a union

I was going through this question to reaffirm my understanding of structure padding.I have a doubt now. When I do something like this:

#include <stdio.h>

#define ALIGNTHIS 16 //16,Not necessarily

union myunion
{
  struct mystruct
  {
    char a;
    int b;
  } myst;
  char DS4Alignment[ALIGNTHIS];
};

//Main Routine
int main(void)
{
  union myunion WannaPad;

  printf("Union's size: %d\n\
       Struct's size: %d\n", sizeof(WannaPad),
      sizeof(WannaPad.myst));

  return 0;
}

Output:

Union's size: 16
Struct's size: 8

should I not expect the struct to have been padded by 8 bytes? If I explicitly pad eight bytes to the structure, the whole purpose of nesting it inside an union like this is nullified.

I feel that declaring a union containing a struct and a character array the size of the struct ought to be but isn't, makes way for a neater code.

Is there a work-around for making it work as I would like it?

Upvotes: 0

Views: 65

Answers (3)

alk
alk

Reputation: 70981

should I not expect the struct to have been padded by 8 bytes?

No, as the struct mystruct is seen/handled on its own. The char had been padded by 3 sizeof (int) -1 bytes to let the int be properly aligned. This does not change, even if someone, somewhere, sometimes decides to use this very struct mystruct inside another type.

Upvotes: 1

RamblingMad
RamblingMad

Reputation: 5518

Think about it logically.

Imagine I had a union with some basic types in it:

union my_union{
    int i;
    long l;
    double d;
    float f;
};

would you expect sizeof(int) == sizeof(double)?

The inner types will always be their size, but the union will always be large enough to hold any of its inner types.

Upvotes: 2

Matt
Matt

Reputation: 15186

By default struct is padded, so int b field is aligned on sizeof(int) boundary. There are several workarounds for this:

  • explicitly use fillers where needed: char a; char _a[sizeof(int)-1]; int b;
  • use compiler-dependent pragma to pack struct on byte boundary
  • use command-line switch etc.

Upvotes: 1

Related Questions