48.8k views
2 votes
For the structure declaration

struct {

char *a;

short b;

double c;

char d;

float e;

char f;

long long g;

void *h;

} foo;

suppose it was compiled on a Windows and UNIX machine, where each primitive data typeof K bytes must have an offset that is a multiple of K.

What are the byte offsets of all the fields in the structure?

User Hasusuf
by
7.8k points

1 Answer

2 votes

Final answer:

Byte offsets of structure members depend on their sizes and alignment rules dictated by the system architecture. Factors such as padding for alignment and the architecture (32-bit or 64-bit) can affect the resulting structure layout.

Step-by-step explanation:

The question revolves around the concept of structure packing in C, particularly how a compiler adheres to alignment restrictions, where each member must be aligned to a byte boundary equal to its size. This mechanism can lead to 'padding' being inserted by the compiler to satisfy alignment requirements.

For the given structure, the byte offsets would be:

  • char *a; - Offset 0
  • short b; - Offset 8 (after padding to align to 2 bytes)
  • double c: - Offset 16 (after 6 bytes of padding to align to 8 bytes)
  • char d; - Offset 24
  • float e: - Offset 28 (after 3 bytes of padding to align to 4 bytes)
  • char f; - Offset 32
  • long long g: - Offset 40 (after 7 bytes of padding to align to 8 bytes)
  • void *h; - Offset 48 (assuming a 64-bit architecture where pointers are 8 bytes, aligned after 8 bytes of padding)

The exact offsets can vary based on the architecture (32-bit vs 64-bit) and compiler specifics, but these offset calculations assume an architecture where pointers are 8 bytes, shorts are 2 bytes, chars are 1 byte, floats are 4 bytes, doubles are 8 bytes, and long longs are also 8 bytes.

User Linus Borg
by
7.8k points