How to allocate two dimensional array?

Consider if you want to allocate a two dimensional array:

int a[10][3];

Then you have to allocate the rows first and then columns using for loops. Here is the C example code.

int **a, x;
//Allocate memory
a = malloc(sizeof(int *) * 10);
for(x = 0; x < 10; x ++) {
      a[x] = malloc(sizeof(int) * 3);
}
 
/* ... */
 
//Deallocate memory
for(x = 0; x < 10; x ++) {
      free(a[x]);
}
free(a);

Leave a Reply