简体   繁体   中英

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

I wonder if it is safe, according to the C99 standard, to interpret such a struct:

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

as an int[3] . Ie is this code snippet sane for all ABIs?

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:

There may be unnamed padding within a structure object, but not at its beginning. (paragraph 15)
There may be unnamed padding at the end of a structure or union. (paragraph 17)

C11, 6.2.5:

An array type describes a contiguously allocated nonempty set of objects with a particular member object type (paragraph 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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