-
-
Save Irene-123/2c2a9c553a35258786ce1953880d0ab9 to your computer and use it in GitHub Desktop.
Dynamically allocating 2D array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
int main(){ | |
int **arr; | |
int rows,cols; | |
printf("\nEnter the number of rows and columns respectively:" ); | |
scanf("%d %d",&rows,&cols ); | |
arr=(int**)malloc(rows*sizeof(int*)); | |
if (arr==NULL){ | |
printf("\nThe space could not be allocated:"); | |
return (0); | |
} | |
for (int i=0;i<rows;i++){ | |
arr[i]=(int*)malloc(cols*sizeof(int)); | |
if (arr[i]==NULL){ | |
printf("\nThe space could not be allocated:"); | |
return (0); | |
} | |
} | |
printf("\nEnter array elements"); | |
for(int i=0;i<rows;i++){ | |
for (int j=0;j<cols;j++){ | |
scanf("%d",&arr[i][j]); | |
} | |
} | |
for (int i=0;i<rows;i++){ | |
printf("\n"); | |
for(int j=0;j<cols;j++){ | |
printf("%d\t", arr[i][j]); | |
} | |
} | |
for (int i=0;i<rows;i++) | |
free(arr[i]); | |
free(arr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment