Is the memory allocated for struct members continguous? What if a struct member is an array?

They will not necessarily be contiguous in memory. This is due to struct padding.

However, in your particular case, it may very well be contiguous. But if you changed the order to something like this:

struct test
{
    char   gender;
    int    age;
    double height;
}

then they most likely will not be. However, in your particular case, you will still likely get padding after gender, to realign the struct to 8 bytes.


The difference between SoA (Struct of Arrays) and AoS (Array of Structs) would be like this:

SoA:

-----------------------------------------------------------------------------------
| double | double | double | *pad* | int | int | int | *pad* | char | char | char |
-----------------------------------------------------------------------------------

AoS:

-----------------------------------------------------------------------------------
| double | int | char | *pad* | double | int | char | *pad* | double | int | char |
-----------------------------------------------------------------------------------

Note that AoS pads within each struct. While SoA pads between the arrays.

These have the following trade-offs:

  1. AoS tends to be more readable to the programmer as each "object" is kept together.
  2. AoS may have better cache locality if all the members of the struct are accessed together.
  3. SoA could potentially be more efficient since grouping same datatypes together sometimes exposes vectorization.
  4. In many cases SoA uses less memory because padding is only between arrays rather than between every struct.

The individual fields are contiguous in the sense that there will be no other variables stored in-between them. They are also guaranteed to be stored in the order that you declared. But the compiler is free to insert padding in-between the individual fields to align things to word boundaries, for instance. So the following:

struct test
{
    double height;
    char   gender;
    int    age;
};

may look like this in memory:

         +7  +6  +5  +4  +3  +2  +1  +0
        +---+---+---+---+---+---+---+---+
0x0000  |            height             |
        +---+---+---+---+---+---+---+---+
0x0008  |      age      |           |gen|
        +---+---+---+---+---+---+---+---+

As for the difference between SoA and AoS, they're laid out exactly as you might imagine.

Tags:

C++

C

Arrays

Struct