Search code examples
c++compilation

Structure with an array, is memory contiguous?


if I have

struct S {
    int a;
    float* b;
    int c;
};

Aside from any padding. a, b (the variable where a pointer is kept), and c will be contiguous. The element that b is pointing to, may be somewhere else in memory

if I have

struct S {
    int a;
    float b[10];
    int c;
};

a, every element of b, and c will all be contiguous in memory. Correct? I wrote a test program and looked at the addresses to confirm, but I am not sure if that is the compiler being helpful or it is guaranteed.


Solution

  • Yes, a, (the elements of) b, and c will be contiguous, if we ignore possible padding between a and b, or b and c. Of course there's no padding between the elements of b.