I want to use this code in a more complex problem, but I didn't get it to work. Why isn't my matrix getting printed?
#include <stdio.h>
#include <stdlib.h>
void print_mat(int **a, int n)
{
printf("\n");
int k,t;
for (k=1;k<=n;k++)
{
for (t=1;t<=n;t++)
printf("%d ", a[k][t]);
printf("\n");
}
}
int main()
{
int i,j,n,**a;
printf("Chess board size=");
scanf("%d", &n);
a=(int **)malloc(n*sizeof(int));
for (i=1;i<=n;i++)
a[i]=(int*)malloc(n*sizeof(int));
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
a[i][j]=-1;
print_mat(a,n);
return 0;
}
You should first malloc for size of int * not int , change
a = ( int ** )malloc( n * sizeof( int ) );
to
a = malloc( n * sizeof( int* ) ); //also no need to cast.
Also, as @Russell Borogove suggested, change loop as for( i = 0; i < n; i++ ) instead of from 1 to n.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With