I was Trying to make 2D Array for Dynamic Allocation of a Matrix in but it crashes When the size of Rows are Bigger Than size of columns. Please Help. Btw I use DevC as A IDE.
//To create a Matrix with user defined value enter its value and display its content
#include<stdio.h>
#include<stdlib.h>
void display(int**,int,int);
int main()
{
int **a,r,c,i,j;
printf("Enter Size of Row of Matrix\n");
scanf("%d",&r);
printf("Enter Size of Column of matrix\n");
scanf("%d",&c);
a=(int**)calloc(r,sizeof(int*));
for(i=0;i<c;i )
{
a[i]=(int*)calloc(c,sizeof(int));
}
printf("Enter Elements of Matrix\n");
for(i=0;i<r;i )
{
for(j=0;j<c;j )
{
printf("Enter Element(%d,%d)\n",i 1,j 1);
scanf("%d",&a[i][j]);
}
}
printf("The Matrix\n");
display(a,r,c);
return 0;
}
void display(int **arr,int r,int c)
{
int i,j;
for(i=0;i<r;i )
{
for(j=0;j<c;j )
{
printf("%d\t",arr[i][j]);
}
printf("\n");
}
}
CodePudding user response:
Here:
a=(int**)calloc(r,sizeof(int*));
for(i=0;i<c;i )
{
a[i]=(int*)calloc(c,sizeof(int));
}
You declare an array of r
elements, but you initialize c
of them. Later you try to write into uninitialized memory, which is Undefined Behavior. Change the loop:
a=(int**)calloc(r,sizeof(int*));
for(i=0;i<r;i )
{
a[i]=(int*)calloc(c,sizeof(int));
}