c - 是否保证相同类型的值之间没有填充?

标签 c struct language-lawyer padding

考虑这段代码:

// T is *any* type
struct str_T{
    T a, b;
};

我知道(几乎总是)在具有不同对齐方式的对象之间存在填充,因为两个成员都是 T 类型。但这一次没有不同的对齐方式。这个断言总能通过吗?

static_assert(sizeof(str_T) == 2 * sizeof(T));
// i.e. padding-free

最佳答案

不,这不能保证。 编译器总是可以决定填充或不填充结构成员之间的额外位。 (除非被覆盖)

引自C11 draft , 6.7.2.1 结构和 union 说明符

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning

关于c - 是否保证相同类型的值之间没有填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47545575/

相关文章:

c - 动态结构数组的 GPU 内存分配

c++ - 使用 boost 图创建结构

json - 如何在没有 rest API key 的情况下将结构转换为 json

c++ - 为什么动态分配的数组不能从列表初始值设定项推断其大小?

Java 内部类和继承 : Is there a duplicate outer this reference?

c - 写入文本文件

c - 如何正确地重新初始化 C 中的循环变量?

c++ - 关于在需要常量表达式的上下文中使用的泛左值常量表达式的问题

c - pthread_join 损坏堆栈中的 pthread_create 参数

c++ - 为什么我的 struct stat 有一个 st_mtim 而不是 st_mtime 字段?