In my last post, I create code to create 2D array in C++. Now, I try to create dynamic 2D array in C. Algorithm to create dynamic 2D array in C or C++ is same. This is a code to create dynamic 2D array in C :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
float **arrayf_create(int row, int col) { int i; float **mat=NULL; /* allocate pointers to rows */ mat = (float **) malloc((row*sizeof(float*))); if (!mat) { fprintf(stderr, "matrixf_create : error allocation row"); exit(0); } /* allocate rows and set pointers to them */ mat[0]=(float*) malloc((row*col)*sizeof(float)); if (!mat[0]) { fprintf(stderr, "matrixf_create : error allocation column"); exit(0); } for(i=1; i<row; i++) mat[i]=mat[i-1] + col; /* return pointer to array of pointers to rows */ return mat; } |
After you create dynamic 2D array in C, you can use this code to free 2D array in C :
1 2 3 4 5 |
void free2Array_float(float **mat) { free (mat[0]); free (mat); } |
My name is Toto Sugito. This is my notes when I try something. Maybe, this is NOT THE BEST SOLUTION for your problems. If you have other method or idea that better with my post, please share in this blog. Thank for visiting my site.