Why don't I see any output if I try to print this 2D array using pointer to pointer?

53 Views Asked by At

I am trying to use pointer to pointer to access a 2D array from a function. But when I run the code it compiles successfully but does not show any output. I can't get where the problem is.

#include <stdio.h>
#define m 3 
#define n 5

void print_2D_mat(int **arr)
{
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++) printf("%d ",*(*(arr+i)+j));
        printf("\n");
    }
}

int main()
{
    int arr[m][n];
    for(int i=0;i<m;i++)
    for(int j=0;j<n;j++) scanf("%d",&arr[i][j]);
    print_2D_mat(arr);
    return 0;
}
1

There are 1 best solutions below

0
On

when you pass a pointer as **arr it doesnt have the information of columns. so it cant stride row wise. correct the code as follows,

#include <stdio.h>
#define m 3
#define n 5

void print_2D_mat(int (*arr)[n])
{
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++) 
        {
            printf("%d ",*(*(arr+i)+j));
        };
        printf("\n");
    }
}

int main()
{
    int arr[m][n];
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
             scanf("%d",&arr[i][j]);
            }
    }
    print_2D_mat(arr);
    return 0;
}