C program to allocate a 2-D array using malloc ( C Interview question - 5)
The question is to allocate a 2 dimensional array using malloc. It should be accesible similar to arrays as a[i][j]
Before going to the code I will just remind the notation of a[i][j]= *(*(a + i) + j)
#include <stdio.h>
int main()
{
int r = 3, c= 3;
int **arr=(int **)malloc(sizeof(int)*r); //allocate memory for rows
int i = 0, j =0;
for ( i = 0; i < r; i++)
{
arr[i] = (int *)malloc(sizeof(int)*c); //allocate memory for columns
}
//store values
for (i = 0; i < r; i++)
{
for(j = 0; j<c;j++)
{
arr[i][j]=i;
}
}
//print values
for (i = 0; i < r; i++)
{
for(j = 0; j<c;j++)
{
printf("%d\n",arr[i][j]);
}
}
for ( i = 0; i <r; i++)
{
free(arr[i]); //free columns first
}
free(arr); //free rows
return 0;
}
Before going to the code I will just remind the notation of a[i][j]= *(*(a + i) + j)
#include <stdio.h>
int main()
{
int r = 3, c= 3;
int **arr=(int **)malloc(sizeof(int)*r); //allocate memory for rows
int i = 0, j =0;
for ( i = 0; i < r; i++)
{
arr[i] = (int *)malloc(sizeof(int)*c); //allocate memory for columns
}
//store values
for (i = 0; i < r; i++)
{
for(j = 0; j<c;j++)
{
arr[i][j]=i;
}
}
//print values
for (i = 0; i < r; i++)
{
for(j = 0; j<c;j++)
{
printf("%d\n",arr[i][j]);
}
}
for ( i = 0; i <r; i++)
{
free(arr[i]); //free columns first
}
free(arr); //free rows
return 0;
}
Comments
Post a Comment