Restore reference to array by pointer. UB or not?

Viewed 74

I am trying to find a way to restore a reference to array through a pointer.

Look at the code:

const int rows = 2;
const int cols = 3;
int arr[rows][cols] = { {1,2,3}, {4,5,6} }; // step0

int(&arr_ref)[rows][cols] = arr; // create a a reference from array - OK

int* some_ptr = &arr[0][0]; // step1. create pointer to array - OK

//int(&arr_ref2)[rows][cols] = *some_ptr; // step2 (failed). restore the array reference from the pointer. impossible.

int(&arr_ref3)[rows][cols] = reinterpret_cast<int(&)[rows][cols]>(*some_ptr); // step2. ok???
  • step0: we have some array
  • step1: create a simple pointer from the array
  • step2: restore reference from the pointer. How to do it properly?

Does using reinterpret_cast lead to undefined behavior somehow if I'm absolutely sure about the size of the array.

Take harder. If we want to get an array of a different size and "shape", but it is for sure within the boundaries of the original array. Is the code below "legal"?

int arr2[6] = { 1,2,3,4,5,6 };
int* some_ptr2 = &arr2[0];
int(&arr2_ref)[2][2] = reinterpret_cast<int(&)[2][2]>(*some_ptr2); // ok???

UPD: If the array contains a complex objects with inheritance, virtual functions etc will it work? Will it be a reliable solution?

1 Answers

You have to cast:

int(&arr_ref2)[rows][cols] = (int(&)[rows][cols])some_ptr;

When you declare the pointer int* some_ptr = &arr[0][0]; you are declaring a pointer to the first int from the array: pointer to one int. So you have to cast the pointer back to the array. And don't reference the pointer (with *some_ptr).

Related