Using Structs Efficiently

February 10, 2010

The order of variable declarations inside a struct can seriously affect its total size. Having a big struct object can limit the efficiency of a program in both memory allocation and execution time, so being attentive to the organization of a struct can actually be quite beneficial.

The following struct declaration is a bad example of how to organize the variables:

struct badStruct {
int i;
double d;
char c;
}

Every instance of this struct would be represented in memory as the following diagram:
Bad Struct Diagram
In which green represents where the integer would be placed, blue represents the double, and red represents the character.

The reason why the double cannot be placed right after the integer, at position 4, lies in the fact that every primitive in C will always sit in a place in memory whose address is a multiple of its size. In other words, double variables will always sit on positions such as 8, 16, 32, etc. Position 4 is not a possible alternative, so the double in this struct has to sit on the next available multiple of 8, therefore leaving empty space unused.

A better way of organizing the variables in this example is shown below:

struct goodStruct {
double d;
int i;
char c;
}

This way, the memory diagram would be something like:
Good Struct Diagram

Notice that the size of the first struct is 24, while the size of the second is 16. They both have unused empty memory spaces after the character variable, and that is because C makes it standard that all objects have to be the size of an exponent of base 2 (1, 2, 4, 8, 16, 32, 64, etc).

Knowing that, even with structs variables inside other structs, it is a good idea to declare the variables in descending order of their sizes. This will minimize the size of the struct, and possibly increase the efficiency of the program.