chi chi - 4 months ago 10
C Question

Define a very large 2D array array with double type

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)

for (i = 0; i < 20; ++i)
    if ((twod[i] = malloc(100000 * sizeof(double))) == NULL)

// clean up
for (i = 0; i < 20; ++i)

The first malloc call allocates space for 20 double pointers. Each double pointer will point to a subarray.

The second malloc call in the loop allocates 100000 doubles in each subarray.

The 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. If malloc returns NULL, then the system is out of memory. This is important since you are allocating HUGE amounts of memory. If malloc returns NULL, the application is aborted.