Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers in C. Why isn't my two-dimensional array printed?

Tags:

c

pointers

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;
}
like image 341
Tudor Ciotlos Avatar asked Jan 27 '26 03:01

Tudor Ciotlos


1 Answers

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.

like image 163
Rohan Avatar answered Jan 28 '26 16:01

Rohan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!