简体   繁体   English

输入punning:int []和struct {int ...}

[英]Type punning: int[] and struct { int … }

I wonder if it is safe, according to the C99 standard, to interpret such a struct: 我想知道根据C99标准来解释这样一个结构是否安全:

struct my_struct_t {
    int a;
    int b;
    int c;
};

as an int[3] . 作为int[3] Ie is this code snippet sane for all ABIs? 即所有ABI的代码片段是否合理?

struct my_struct_t f;
int *i = &f.a;
i[0] = 1; // f.a == 1
i[1] = 2; // f.b == 2
i[2] = 3; // f.c == 3

As far as I understand the standard, the compiler is allowed to add padding after members in a struct, but there must not be any padding inside an array. 据我所知,标准,允许编译器在结构中的成员之后添加填充,但是数组内部不得有任何填充。 Am I getting that right? 我做对了吗? (If I am, then the code example would yield undefined behavior.) (如果是,那么代码示例将产生未定义的行为。)

The only real "answer" to this is a citation: 对此唯一真正的“答案”是引用:

C11, 6.7.2.1: C11,6.7.2.1:

There may be unnamed padding within a structure object, but not at its beginning. 结构对象中可能存在未命名的填充,但不是在其开头。 (paragraph 15) (第15段)
There may be unnamed padding at the end of a structure or union. 结构或联合的末尾可能有未命名的填充。 (paragraph 17) (第17段)

C11, 6.2.5: C11,6.2.5:

An array type describes a contiguously allocated nonempty set of objects with a particular member object type (paragraph 20) 数组类型描述了具有特定成员对象类型的连续分配的非空对象集(第20段)

Since the subscript operator is exactly equivalent to a pointer arithmetic operation, it cannot take account of padding (external to the type of the target object, anyway) where any may exist, and in a struct, it may. 由于下标运算符完全等效于指针算术运算,因此它不能考虑任何可能存在的填充(无论如何都是目标对象的类型),并且在结构中,它可以。

As int s are, well, int -aligned, I think it should work (and it does on my Intel x86-64 with gcc on Linux) on most platforms. 正如int s,嗯, int -aligned,我认为它应该在大多数平台上工作(并且它在我的Intel x86-64上使用gcc在Linux上运行)。

You can check if it works at compile time: 您可以在编译时检查它是否有效:

static_assert(offsetof(struct my_struct_t, c) == 2*sizeof(int));

Iff this assertion doesn't fail, the standard guarantees that you're safe (if I'm not terribly mistaken, but I can't think of anything making it UB). 如果这个断言没有失败,标准保证你是安全的(如果我不是非常错误,但我想不出任何使它成为UB的东西)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM