如果 char[] 在结构 __attribute__((aligned)) 内,char[] 的步幅是否保证为 1?
Is the stride of a char[] guaranteed to be 1 if the char[] is inside a struct __attribute__((aligned))?
假设我有一个看起来像这样的结构
(事实证明,这在现实世界中很常见):
struct foo {
char[24] bar;
uint32_t fnord;
uint32_t quux;
}__attribute__((aligned(4));
bar
的步幅是多少,即&bar[1] - &bar[0]
是多少,
鉴于它在 struct foo
中?
这对 sizeof(foo)
有影响,我很确定我想要
为 32,我还希望在 foo.fnord
和 foo.quux
上进行良好的快速对齐操作,否则它不会首先对齐。
根据标准 paragraph 6.2.5/20,
An array type describes a contiguously allocated nonempty set of
objects with a particular member object type
(强调已添加。)因此,数组的元素在内存中始终是连续的。这是数组的定义特征之一。链接、存储 class、另一个数据结构中的成员资格、数组本身或包含它的任何数据结构的对齐要求 -- none 这些都会影响数组元素的连续性。
数组的对齐要求通常是其元素类型的倍数,因此对齐数组本身也会对齐其所有元素。在任何情况下,数组元素都不受单独对齐的约束。
假设我有一个看起来像这样的结构 (事实证明,这在现实世界中很常见):
struct foo {
char[24] bar;
uint32_t fnord;
uint32_t quux;
}__attribute__((aligned(4));
bar
的步幅是多少,即&bar[1] - &bar[0]
是多少,
鉴于它在 struct foo
中?
这对 sizeof(foo)
有影响,我很确定我想要
为 32,我还希望在 foo.fnord
和 foo.quux
上进行良好的快速对齐操作,否则它不会首先对齐。
根据标准 paragraph 6.2.5/20,
An array type describes a contiguously allocated nonempty set of objects with a particular member object type
(强调已添加。)因此,数组的元素在内存中始终是连续的。这是数组的定义特征之一。链接、存储 class、另一个数据结构中的成员资格、数组本身或包含它的任何数据结构的对齐要求 -- none 这些都会影响数组元素的连续性。
数组的对齐要求通常是其元素类型的倍数,因此对齐数组本身也会对齐其所有元素。在任何情况下,数组元素都不受单独对齐的约束。