Arithmetic of a pointer between consecutive members of the same type in the structure used for ordinary practice, while arithmetic of a pointer is valid only inside the array. In C ++, it will be explicitly Undefined Behavior, because an array can only be created by a declaration or a new expression. But the C language defines an array as an adjacent non-empty set of objects with a specific type of member object called the element type. (project n1570 for C11, 6.2.5 types Β§20). Thus, we can make sure that the members are consecutive (which means there are no spaces between them), it may be legal to see this as an array.
Here is a simplified example that compiles without warning and gives the expected results at run time:
#include <stdio.h>
#include <stddef.h>
#include <assert.h>
struct quad {
int x;
int y;
int z;
int t;
};
int main() {
static_assert(offsetof(struct quad, t) == 3 * sizeof(int),
"unexpected padding in quad struct");
struct quad q;
int *ix = &q.x;
for(int i=0; i<4; i++) {
ix[i] = i;
}
printf("Quad: %d %d %d %d\n", q.x, q.y, q.z, q.t);
return 0;
}
, , .
:
static_assert, ?
( 1) -, . . , ( t), 3 sizeof(int) . 3 * sizeof(int), struct
, , , , UB, +1 , , ,