Can an array of single-member structure objects be interpreted as an array of their subobjects?

Viewed 82

In the following program, an array of objects of structure type, wherein each object comprises a sole subobject of type int, is initialized by a function which treats it as an array of ints:

#define N 8
void init_arr(int* arr)
{
    for (int i = 0; i < N; ++i)
        arr[i] = i;
}
int main()
{
    struct { int i; } arr[N];
    init_arr((int*)arr);
}

Is this well-defined in C?

My suspicion is that the cast of arr to int* in the call to init_arr is well-defined (per C99 6.3.2.1.3 [array-to-pointer conversion] followed by 6.7.2.1.13 [structure-member pointer interconvertibility]), but results in a pointer to a member subobject, not an array element. Even if such an object is treated as the element of a single-element array (for the purposes of pointer arithmetic), subscripting on its pointer produces a defined result only when the index is 0. Is my understanding correct? Is there any way to make this well-defined without modifying init_arr or resorting to passing a plain array of ints (then copying to arr element by element)?

Bonus: What about in C++?

0 Answers
Related