0

As the title indicates, i want to get the number of offset in bytes of a union member from other members before that member ( using the offsetof macro defined in stddef.h ). This worked for structs as expected

#include <stdio.h>
#include <stddef.h>

struct bio {
  int age;
  char name;
};


int main( void ) {
  printf("%d\n", offsetof(struct bio, name));  // result is 4 , which is what i expected
}

but for unions it printed 0

#include <stdio.h>
#include <stddef.h>

union bio {
  int age;
  char name;
};


int main( void ) {
  printf("%d\n", offsetof(union bio, name)); // 0
}

Just a follow up question, the reason for this behavior is it because the members of a union are stored at the same block of memory ?

As par this explanation wikipedia offsetof i was also expecting to get a value of 4 not 0

0.sh
  • 2,659
  • 16
  • 37

2 Answers2

3

In union the space allocated is the maximum of the bytes needed for each field in the union itself. So for bio (assuming sizeof(int)=4):

sizeof(bio) = max(sizeof(int), sizeof(char)) = sizeof(4, 1) = 4

This is because all union fields share the same memory space, which starts at the beginning of the union itself.

bio.age = 24
bio.name = 'a' //a will use the first byte in the union, just like the first byte of the integer

You can check it by printing pointers as well.

Koldar
  • 1,317
  • 15
  • 35
3

By definition, a union describes an overlapping nonempty set of member objects, such that the members share the same memory location. This means that the address of each member is the same. Further, the address of such a member is - by definition - the same as that of the union object itself, and consequently the offset of each member must be 0 (cf, for example this online C standard draft; emphasis are mine):

6.7.2.1 Structure and union specifiers

16.) The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit- field, then to the unit in which it resides), and vice versa.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58