How can I convert an array of 25 elements into a 5x5 2D array?

Printable View

- 05-15-2008TupciaArray -> 2D array
How can I convert an array of 25 elements into a 5x5 2D array?

- 05-15-2008Elysia
Create 2D array, then loop through start to end and set individuals elements.

- 05-15-2008King Mir
You could cast the addresses:

Code:`typedef int array2d [5][5];`

*(array2d *)&myArray1D;

Code:`*(int (*)[5][5])&myArray1D`

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-2008VirtualAceQuote:

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-16-2008matsp
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;`

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;

}

}

}

--

Mats