Write a program to allocate memory for the 2-dimensional array dynamically.
#include<stdio.h> #include<stdlib.h> int main() { int i,j,r,c,**p; printf("Enter row size = "); scanf("%d",&r); printf("Enter column size = "); scanf("%d",&c); p = (int**)malloc(sizeof(int*) * r); for(i = 0;i < r;i++) { p[i] = (int*)malloc(sizeof(int)*c); } printf("Enter %d Elements\n",r*c); for(i = 0;i < r;i++) { for(j = 0;j < c;j++) scanf("%d",&p[i][j]); } printf("Array Elements are\n"); for(i = 0;i < r;i++) { for(j = 0;j < c;j++) printf("%d ",p[i][j]); printf("\n"); } for(i = 0;i < r;i++) { free(p[i]); } free(p); p = NULL; return 0; }
Output
Enter row size = 3 Enter column size = 4 Enter 12 Elements 1 2 3 4 5 6 7 8 9 4 5 2 Array Elements are 1 2 3 4 5 6 7 8 9 4 5 2