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);
Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in