Dynamic allocation of a 2D array | 2D Array Allocation Dynamically | Multi Dimension Array Dynamic Allocation

Dynamic allocation of a 2D array | 2D Array Allocation Dynamically | Multi Dimension Array Dynamic Allocation






main (void)
{
int nrows, ncols, i, j;
int **numbers; /* pointer to the first cell ([0][0]) */

printf ("How many rows and columns?> ");
scanf ("%d%d", &nrows, &ncols);

/* allocating the array of pointers */
numbers = (int **) calloc (nrows, sizeof(int *));

/* allocating the array of integers */
for (i=0; i<nrows; ++i)
numbers[i] = (int *) calloc (ncols, sizeof(int));

i=1; j=1;
numbers[i][j] = 9; /* initializes one value to 9 */


for (i=0; i<nrows; i=i+1)
{
for (j=0; j<ncols; j=j+1)
{
printf ("%3d ", numbers[i][j]);

}
printf ("\n");
}

/* freeing the array */
for (i=0; i<nrows; ++i)
free (numbers[i]);

free (numbers);

return (0);
}

1 comment: