How can I convert an array of 25 elements into a 5x5 2D array?
Printable View
How can I convert an array of 25 elements into a 5x5 2D array?
Create 2D array, then loop through start to end and set individuals elements.
You could cast the addresses:
Or without typedefs:Code:typedef int array2d [5][5];
*(array2d *)&myArray1D;
Or if passed to a function, simply cast the 1D array to void pointer.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.
You never 'need' a 2D array per se.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.
What bubba means is that you can make any dimension array using math: The index of an X-dimension array is:
where p{0..X} is the position of that dimension, and n{0..X} is the size of that dimension.Code:index = p0 + p1 * n0 ... pX *n(X-1) * n(X-2) ... n0;
Example:
This will be exactly what the compiler does internally anyways, when it deals with multidimensional arrays.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