Allocation 2D arrays in C (and freeing memory)

By convention, when dealing with 2D array, the first dimension refer to the rows, and the second to the columns.

To create a 2D array (double pointer) in C, you first create a 1D array of pointers (rows), and then, for each row, create another one dimensional array (columns):

    double** array;  
    array = (double**) malloc(nX*sizeof(double*));  
    for (int i = 0; i < nX; i++)  
    {
       array[i] = (double*) malloc(nY*sizeof(double));  
       /* then array[i][j] = values */
    }

At the end, do not forget to free the memory, each row that has been created, and then the array pointer itself:

    for (i = 0; i < nX; i++){  
       free(array[i]);  
    }     
 free(array);
Please follow and like us:
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *