Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to cast pointer to struct to array pointer

Given an aggregate struct/class in which every member variable is of the same data type:

struct MatrixStack {
    Matrix4x4 translation { ... };
    Matrix4x4 rotation { ... };
    Matrix4x4 projection { ... };
} matrixStack;

How valid is it to cast it to an array of its members? e.g.

const Matrix4x4 *ptr = reinterpret_cast<const Matrix4x4*>(&matrixStack);
assert(ptr == &matrixStack.translation);
assert(ptr + 1 == &matrixStack.rotation);
assert(ptr + 2 == &matrixStack.projection);
auto squashed = std::accumulate(ptr, ptr + 3, identity(), multiply());

I am doing this because in most cases I need named member access for clarity, whereas in some other cases I need to pass the an array into some other API. By using reinterpret_cast, I can avoid allocation.

like image 771
Ben Avatar asked Oct 19 '22 02:10

Ben


1 Answers

The cast it not required to work by the standard.

However, you can make your code safe by using static asserts that will prevent it from compiling if the assumptions are violated:

static_assert(sizeof(MatrixStack) == sizeof(Matrix4x4[3]), "Size mismatch.");
static_assert(alignof(MatrixStack) == alignof(Matrix4x4[3]), "Alignment mismatch.");
// ...
const Matrix4x4* ptr = &matrixStack.translation;
// or
auto &array = reinterpret_cast<const Matrix4x4(&)[3]>(matrixStack.translation);
like image 136
Maxim Egorushkin Avatar answered Nov 09 '22 23:11

Maxim Egorushkin