0

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;
}
Nakib
  • 19
  • 4
  • 2
    An array of arrays is not the same as an array of pointers. [Pay attention to your compiler warnings](https://godbolt.org/z/nsWcbcGe6) and treat them *all* as errors, because that's exactly what the are. In this specific instance, change `print_2d_mat` to `void print_2D_mat(int (*arr)[n])` and it should do what you seek. – WhozCraig Mar 20 '22 at 03:56
  • I don't get the problem here, can't I access an array of arrays using pointer in this way?@WhozCraig – Nakib Mar 20 '22 at 03:59
  • They're not the same, so no, you can't. `arr` in `main` is a native array of arrays. Your function expects a pointer to pointer. They're not the same, nor even compatible. And the warnings-as-errors I linked in my first comment calls that out. – WhozCraig Mar 20 '22 at 04:01
  • Can I access 2D array without declaring n globally? @WhozCraig – Nakib Mar 20 '22 at 04:06
  • We can use *arr but can't use **arr. Can you explain a little bit?@WhozCraig – Nakib Mar 20 '22 at 04:26

1 Answers1

0

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;
}
balu
  • 1,023
  • 12
  • 18