# Array -> 2D array

• 05-15-2008
Tupcia
Array -> 2D array
How can I convert an array of 25 elements into a 5x5 2D array?
• 05-15-2008
Elysia
Create 2D array, then loop through start to end and set individuals elements.
• 05-15-2008
King Mir
Code:

```typedef int array2d [5][5]; *(array2d *)&myArray1D;```
Or without typedefs:
Code:

`*(int (*)[5][5])&myArray1D`
Or if passed to a function, simply cast the 1D array to void pointer.

But if you need a 2d array, why do you have a 1D array? You should probably be loading your data directly into a 2d array in the first place.
• 05-15-2008
VirtualAce
Quote:

But if you need a 2d array, why do you have a 1D array? You should probably be loading your data directly into a 2d array in the first place.
You never 'need' a 2D array per se.
• 05-16-2008
matsp
Quote:

Originally Posted by Bubba
You never 'need' a 2D array per se.

What bubba means is that you can make any dimension array using math: The index of an X-dimension array is:
Code:

`index = p0 + p1 * n0 ... pX *n(X-1) * n(X-2) ... n0;`
where p{0..X} is the position of that dimension, and n{0..X} is the size of that dimension.

Example:
Code:

```// Treat a 1d 1000 element array as a 3D [10][10][10] array. int array[1000];  int x, y, z; for(x = 0; x < 10; x++) {   for(y = 0; y < 10; y++)   {       for(z = 0; z < 10; z++)       {           array[x + (y * 10) + (z * 100)] = x * y * z;       }   } }```
This will be exactly what the compiler does internally anyways, when it deals with multidimensional arrays.

--
Mats