How do I make a dynamic 2d array in C with malloc realloc and free?
How do I make a dynamic 2d array in C with malloc realloc and free?
(1) You can google to find out.
(2) You can use a 1D array (as 2D arrays and 1D arrays are fundamentally the same thing). You just need to do access arithmetic yourself, which is not something hard.
(3) You can use an array of pointers and allocate memory of appropriate size for each.
(4) You can use a double pointer method which is similar to using (2) and (3) together.
I don't know of any other methods, if any.
"Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." - Rick Cook, The Wizardry Compiled
The malloc and free of arrays, in various ways.
Code:#include <stdio.h> #include <stdlib.h> void f1(void) { int a[10]; int *b = malloc(10*sizeof(*b)); /// free(b); } // If the minor dimension is always fixed void f2(void) { int a[10][20]; int (*b)[20] = malloc(10*sizeof(*b)); /// free(b); } // variable in both dimensions void f3(void) { int a[10][20]; int **b = malloc(10*sizeof(*b)); for( int i = 0 ; i < 10 ; i++ ) b[i] = malloc(20*sizeof(*b[i])); /// for ( int i = 0 ; i < 10 ; i++ ) free(b[i]); free(b); } // variable in both dimensions, but all rows the same void f4(void) { int a[10][20]; int **b = malloc(10*sizeof(*b)); b[0] = malloc(10*20*sizeof(*b[0])); for( int i = 1 ; i < 10 ; i++ ) b[i] = b[i-1] + 20; /// free(b[0]); free(b); } int main ( ) { f1(); f2(); f3(); f4(); }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.