Allocate space using malloc in 2D Pointer
Implementation in C:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int **array,nrows,ncols,i,j;
printf("\n Enter number of rols and columns for matrix:\n");
scanf("%d%d", &nrows, &ncols);
array =malloc(nrows*sizeof(int*));
for(i=0;i<nrows;i++)
{
array[i] = malloc(ncols*sizeof(int*));
}
printf("\n Enter Matrix data: \n");
for(i=0; i<nrows; i++)
{
for(j=0; j<ncols; j++)
{
scanf("%d", &array[i][j]);
}
printf("\n");
}
if(array == NULL)
{
printf("Out of memory");
exit(0);
}
printf("\n Print Matrix data: \n");
for( i=0; i<nrows; i++)
{
for(j=0; j<ncols; j++)
{
printf("%d", array[i][j]);
printf(" ");
}
printf("\n");
}
}
#include<stdio.h>
#include<stdlib.h>
void main()
{
int **array,nrows,ncols,i,j;
printf("\n Enter number of rols and columns for matrix:\n");
scanf("%d%d", &nrows, &ncols);
array =malloc(nrows*sizeof(int*));
for(i=0;i<nrows;i++)
{
array[i] = malloc(ncols*sizeof(int*));
}
printf("\n Enter Matrix data: \n");
for(i=0; i<nrows; i++)
{
for(j=0; j<ncols; j++)
{
scanf("%d", &array[i][j]);
}
printf("\n");
}
if(array == NULL)
{
printf("Out of memory");
exit(0);
}
printf("\n Print Matrix data: \n");
for( i=0; i<nrows; i++)
{
for(j=0; j<ncols; j++)
{
printf("%d", array[i][j]);
printf(" ");
}
printf("\n");
}
}
Comments
Post a Comment