Allocating two dimensional array dynamically using C

One of the most common interview questions asked in interview is to dynamically allocate a 2-D array,

The following code is dynamically allocating  a 2-D array

#include 
int main()
{
      int **pointer;
      pointer = (int **) malloc(rows *sizeof(int *));
      if (pointer == NULL) {
         perror("Failed to allocate\n");
         return -1;
      }else {
         int i;
         for (i = 0; i < rows; i++) {
             pointer[i] = (int *)malloc(columns*sizeof(int));
             if (pointer[i] == NULL) {
                perror("Failed to allocate\n");
                return -1;
           }
   }

}


Now you can use pointer in similar syntax of two dimensional array.
Eg: pointer[i][j];

Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto