-1

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.

  • The attribute does nothing special, none of the struct members are larger than 4. You might as well omit it. Feel better with #if sizeof foo != 32 \ #error "gack" \ #endif in your code. – Hans Passant Dec 08 '18 at 10:02
  • if sizeof doesn't work: https://stackoverflow.com/questions/4079243/how-can-i-use-sizeof-in-a-preprocessor-macro – David Calman Dec 10 '18 at 03:34

1 Answers1

0

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.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • so why do arrays of structs with odd sizes have strides of the next power of 2 unless you say `packed`? We know the compiler is allowed to pad structs in an array, can it pad types smaller than the alignment size like `char`? – David Calman Dec 08 '18 at 08:47
  • "In no case are array elements subject to individual alignment." What if the compiler decides to pad an odd-sized struct in an array, but not tell you so in `sizeof(struct odd_sized_struct_t)`? What if they're parallel arrays (which C also supports)? Why are chars not padded at the end of an element like structs are? – David Calman Dec 08 '18 at 08:55
  • @DavidCalman, The compiler *does not* pad structs in arrays. It pads structs, if necessary, **period**. It does this proactively, so that it can form arrays of structs that comply with the contiguity requirement, and whose sizes are multiples of the struct's alignment requirement. When it does this, the padding is part of the struct size reported by `sizeof`. – John Bollinger Dec 08 '18 at 16:41
  • As for "parallel arrays", I'm afraid you'll have to clarify. That particular term is not used in the standard, and I'm not sure how to interpret it such that it would have any bearing on the question at hand. – John Bollinger Dec 08 '18 at 16:42