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
Now you can use pointer in similar syntax of two dimensional array.
Eg: pointer[i][j];
The following code is dynamically allocating a 2-D array
#includeint 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
Post a Comment