Search code examples
cstructsizeofmemory-alignmentstride

Is the stride of a char[] guaranteed to be 1 if the char[] is inside a struct __attribute__((aligned))?


So let's say I have a struct that looks like this (pretty common in the real world, it turns out):

struct foo {
    char[24] bar;
    uint32_t fnord;
    uint32_t quux;
}__attribute__((aligned(4));

What is the stride of bar, that is, what is &bar[1] - &bar[0], given that it's in struct foo? This has implications for sizeof(foo), which I'm pretty sure I wanted to be 32, and I also wanted nice fast aligned operations on foo.fnord and foo.quux, or it wouldn't be aligned in the first place.


Solution

  • Per paragraph 6.2.5/20 of the standard,

    An array type describes a contiguously allocated nonempty set of objects with a particular member object type

    (Emphasis added.) Thus, the elements of an array are always contiguous in memory. That is among the defining characteristics of an array. Linkage, storage class, membership in another data structure, alignment requirement of the array itself or of any data structure containing it -- none of these affect array elements' contiguity.

    The alignment requirement of an array is normally a multiple of that of its element type, so that aligning the array itself also aligns all its elements. In no case are array elements subject to individual alignment.