Hey all! Is type punning from a dynamically allocated array of structs T to a std::array<T, N> UB when N is known? For example:
#include <array>
#include <iostream>
#define T_ARRAY_SIZE 10 // definitely a constant but lets suppose it was a runtime value.
struct T { int data; };
int main() {
T* tArray = new T[T_ARRAY_SIZE]; // create T C style dyn-alloc'd array
for (int i = 0; i < T_ARRAY_SIZE; i++) { // fill array the C way
tArray[i].data = i + 1;
}
const std::array<T, 10>* const tStdArray = reinterpret_cast<std::array<T, 10>*>(tArray); // shady reinterpret not withT_ARRAY_SIZE but with 10 because we magically know it will be 10
for (int i = 0; i < tStdArray->size(); i++) { // print values (do some work) using std::array api
std::cout << (*tStdArray)[i].data << std::endl;
}
delete[] tArray;
return 0;
}```
It obviously works with x86-64 GCC (trunk) and clang (trunk) on godbolt.org (https://godbolt.org/z/YsaxKo1Gs). However, is this even legal in GCC, clang and MSVC? Would relying on this behavior be bad? Would the same piece of code work if `tArray` were to be obtained from an `std::vector<T>`? Please offer your insights!
P.S. I'm doing this because I have one piece of 3rd party code giving me a C style dynamic array of `T` and another piece of 3rd party code expecting an `std::array<T, N>` (N is template parameter).