Node:Unwarranted assumptions about storage, Next:, Previous:Confusing foo++ and ++foo, Up:Run-time errors

Unwarranted assumptions about storage

Do not assume that the size of a structure is the sum of the sizes of its parts. The two may differ for various reasons; for example, the operating system may be aligning variables with specific addresses within the data structure. Furthermore, the elements of an array may not even be next to one another in memory.

This kind of code is always safe:

int my_array[3];

my_array[0] = 0;
my_array[1] = 0;
my_array[2] = 0;

This kind of code is not:

int my_array[3];

*my_array = 0;
*(my_array + (1 * sizeof(int))) = 0;
*(my_array + (2 * sizeof(int))) = 0;

While it is true that the variable my_array used without its square brackets is a pointer to the first element of the array, you must not assume that you can simply calculate a pointer to the third element with code like the following:

my_array + 2 * sizeof(int);

Do something like this instead: