Originally Posted by
C_ntua
There is a "nicer" way to allocate a 2d, 3d etc array. It has also the advantage that is mallocs one space of memory, so it will be more effective. And that it requires two lines of code
Code:
int *array3d = malloc(X * Y * Z * sizeof(int));
#define array3d(x, y, z) array[(x) + (y * X) + (z * X * Y)]
The only downside is that if you have a function that requires ***int you won't be able to pass array3d.
(Note: you should have had "int *array" instead of "int *array3d".)
Why not? A multi-dimensional array is represented exactly like that in memory, so you should be able to do it with a cast. Something like this:
Code:
#include <stdio.h>
#include <stdlib.h>
enum { X = 3, Y = 4 };
void print2d(int array[X][Y], int X, int Y) {
int x, y;
for(x = 0; x < X; x ++) {
for(y = 0; y < Y; y ++) {
printf("%2i", array[x][y]);
if(y + 1 < Y) putchar(' ');
}
putchar('\n');
}
}
int main() {
int *array = malloc(X * Y * sizeof(*array));
int x;
/* because it's really just a 1D array */
for(x = 0; x < X * Y; x ++) {
array[x] = x;
}
/* ... but now, treat it like a 2D array */
print2d((int **)array, X, Y);
free(array);
return 0;
}
It gives a warning, yes, but that's surely to be expected . . . .