Structures, Holes, and Unions in C

LAST EDIT: 10 Iyar 5761 (2001/05/03)

When you have a data area where you would like to access both as one long byte buffer, and as a data structure composed of different types, then you'll probably want to use a combination of the struct and union in C.

Note that a struct can leave holes. Some hardware platforms require that multi-byte variables (e.g., int, long int) start at addresses that are multiples of 2 or 4 bytes, and will insert unused bytes between adjacent variables to enforce this.

Here are some programs that demonstrate this. They differ in the data structures used as an example:

  1. General data structure
  2. similar to a TFTP data packet
  3. similar to a TFTP request packet
These programs also shows the following:

After studying the short program, you should compile and run the programs, and study the output. Ideally, you should run them on different platforms, but currently JCT only makes Linux available to you.

Some/most compilers have ways of telling the compiler not to insert holes between variables. Here is how to do it in GNU C