How can I convert an array of 25 elements into a 5x5 2D array?
How can I convert an array of 25 elements into a 5x5 2D array?
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.
Last edited by King Mir; 05-15-2008 at 01:07 PM.
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.
You never 'need' a 2D array per se.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
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.