Search code examples
cmemorymemory-management

Difference in memory in Array and Structures?


What is the difference between memory layout when I allocate some memory like:

float arr[3];

and

struct vals {
    float x, y, z;
};

I know that when allocating memory in arrays, it is contiguous. But I am confused about the structs... It feels that it will be, and I have tested that with less number of members of structs. an example from raylib here also makes me confident. But still, is there any edge cases where the allocated memory is not contiguous or not allocated in the same order of declaration due to some optimization?


Solution

  • In the case of a struct with consecutive members of the same type, it's likely that they will be allocated contiguously in memory but not guaranteed.

    Also, by the rules of pointer arithmetic, it's valid to do this:

    *(&arr[0] + 1) = 2.0;
    

    But undefined behavior if you do this:

    struct vals v;
    *(&v.x + 1) = 2.0;