In C/C++ suppose I define a simple struct named test
as follows.
struct test { double height; int age; char gender; }
For a specific instance of this struct say test A
are A.height, A.age, A.gender
contiguous in memory?
More generally, how do the layouts in memory for a Structure of Arrays and an Array of structures look like? A picture would be really helpful.
If we create an object of some structure, then the compiler allocates contiguous memory for the data members of the structure. The size of allocated memory is at least the sum of sizes of all data members. The compiler can use padding and in that case there will be unused space created between two data members.
The memory can be allocated using the malloc() function for an array of struct . This is called dynamic memory allocation. The malloc() (memory allocation) function is used to dynamically allocate a single block of memory with the specified size. This function returns a pointer of type void .
A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.
This tells the compiler how big our struct is and how the different data items (“members”) are laid out in memory. But it does not allocate any memory. To allocate memory for a struct, we declare a variable using our new data type.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With