IHYPRESS PROGRAMMING
Tutorials and C programs with code and output for beginners
c programming
HOME | ASP | C | CSS | GNUPLOT | HTML | JAVASCRIPT | PERL | PHP | PYTHON | RUBY | SVG
CMulti-Dimensional Arrays : Dynamic Allocation II
<09.06>
/* Dynamic allocation of a 2D array */
/* (Computer Scientist's Method) */
#include <stdio.h> #include <stdlib.h> /* Dynamic allocation of arrays of more than one dimension can also be done using a pointer pointing to an array of pointer and each pointer of that array pointing to an array of values. With that method you can use the real 2-D subscripts like array[i][j] */ int 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); }
Hergestellt in Deutschland / Made in Germany
How many rows and columns?> 4 9 0 0 0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
COPYRIGHT © 2015-2024 IHY PRESS Frankfurt am Main 60329 Deutschland