When you want a rectangular 2D array, another option to consider is to create a huge array of the objects that you want, then create another array of pointers to point to these objects at regular intervals. You then access this second array as a 2D array of the objects that you want. The advantage here is that you would only need to allocate memory twice. Building on Adak's example:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *data;
int **mat;
int rows, cols, i, j;
printf("How many rows do you want? ");
scanf("%d", &rows);
getchar(); /* remove newline from input stream */
printf("And how many columns? ");
scanf("%d", &cols);
getchar(); /* removes the left over newline */
/* Lazy, so assume that malloc always succeeds */
data = malloc(rows * cols * sizeof(*data));
mat = malloc(rows * sizeof(*mat));
for (i = 0; i < rows; i++) {
mat[i] = data + (i * cols);
}
/* Assign and print some test values */
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
mat[i][j] = i * j;
printf("%4d ", mat[i][j]);
}
putchar('\n');
}
/* Done, so cleanup */
free(mat);
free(data);
printf("\n\n");
getchar(); /* hold the terminal window open */
return 0;
}