I want to define a 2D array with size 20*100000 in C. I do not want to keep the size fixed.
double **twod = malloc(20 * sizeof(double *)); int i; if (twod == NULL) abort(); for (i = 0; i < 20; ++i) if ((twod[i] = malloc(100000 * sizeof(double))) == NULL) abort(); // clean up for (i = 0; i < 20; ++i) free(twod[i]); free(twod);
malloc call allocates space for 20
double pointers. Each
double pointer will point to a subarray.
malloc call in the loop allocates 100000
doubles in each subarray.
free calls do the inverse of
malloc--they return memory to free store. First, each subarray must be freed, in a loop. Then the entire array itself must be freed too.
The return value of
malloc is examined against
NULL, then the system is out of memory. This is important since you are allocating HUGE amounts of memory. If
NULL, the application is aborted.