Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to use an array to access multiple arrays of different length in C++

Tags:

c++

arrays

I have several two dimensional arrays of various, differing lengths:

int Array_A[][2] = {{...}, {...}, {...}, ...};
int Array_B[][2] = {{...}, {...}, ...};
int Array_C[][2] = {{...}, ...};

I need another array which allows me to access these arrays:

??? Full_Array[] = {Array_A, Array_B, Array_C};

What is the correct type of ??? that I should use? I tried uint** and uint* but neither works.

If it's not doable, suppose I am not allowed to change the definition of Array_A, Array_B, ... What is a good way to define Full_Array?

like image 340
stanleyli Avatar asked Jan 05 '23 05:01

stanleyli


2 Answers

Array_A, Array_B, and Array_C are all arrays of arrays of 2 ints, so they can all undergo the array-to-pointer conversion at the top level into pointer to array of 2 ints.

So Full_Array needs to be an array of pointers to arrays of 2 ints. The declaration can be written:

int (*FullArray[])[2] = {Array_A, Array_B, Array_C};

Note that there is no way to tell what the lengths of the subarrays are, unless you have sentinel values.

like image 163
Brian Bi Avatar answered Feb 06 '23 19:02

Brian Bi


If the arrays Array_A, Array_B, and Array_C are of the same size, you can create pointers to them using the & operator and store them in an array. If they are of different sizes, the & operator will create different pointer types and you won't be able to store them in the pointer array.

int Array_A[3][2] = { ... };
int Array_B[3][2] = { ... };
int Array_C[3][2] = { ... };

typedef int (*PtrType)[3][2];
PtrType Full_Array[] = {&Array_A, &Array_B, &Array_C};

The following will be an error.

int Array_A[][2] = { {}, {}, {} }; // Implied dimensions [3][2]
int Array_B[][2] = { {}, {} };     // Implied dimensions [2][2]
int Array_C[][2] = { {}, {}, {} }; // Implied dimensions [3][2]

typedef int (*PtrType)[3][2];
PtrType Full_Array[] = {&Array_A, &Array_B, &Array_C};
like image 25
R Sahu Avatar answered Feb 06 '23 21:02

R Sahu