Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

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

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...