are non array values continuous in memory?

Hey guys,

afaik data in memory is continuous if i declare e.g a array.
But is it also guaranteed that data. e.g Integers are continuous if they are declared & initialized after each other?

1
2
3
4
5
6
7
class MyClass
{
  public:
    int x;
    int y;
    int z;
}


Last edited on
No, it's not guaranteed that the integers are continuous in memory in terms of alignment/padding:

https://en.wikipedia.org/wiki/Data_structure_alignment
is there a way to make them continuous except arrays/containers?
the only guarantee you have is that the addresses of the data members with the same access (all publics, all privates, etc) grow in order of declaration.

However, all sensible compilers will have no padding between those ints, so you can write a static_assert in case your code finds itself somewhere where that is not true

1
2
3
4
5
6
7
8
class MyClass // make sure to update the static_assert after this class definition when making any changes
{
  public:
    int x;
    int y;
    int z;
};
static_assert(sizeof(MyClass) == 3*sizeof(int), "does your compiler seriously pad between same-type same-access members?");


Or just use std::array<int, 3>
Do you have some specific case that requires continuousness?
ok good to know.
I had no idea that such padding exists x.x
Topic archived. No new replies allowed.