0

Recently I had stuck in a problem i.e passing 2D array with pointers, the code I am trying to execute -

#include<iostream>
using namespace std;

int const m=3;
int const n=2;
int const p=3;

void input(int **a,int f, int k)
{
    int i,j;
    for(i=0;i<f;i++)
    {
        for(j=0;j<k;j++)
        {
            cin>>a[i][j];
        }
    }
    return;
}

int main()
{
    int a1[m][n];
    input(a1,m,n);
}

but getting error as -

main.cpp:24:14: error: cannot convert ‘int (*)[2]’ to ‘int**’ for argument ‘1’ to ‘void input(int**, int, int)’
  input(a1,m,n);
              ^

after that I tried this code and it runs successfully-

#include<iostream>
using namespace std;

int const m=3;
int const n=2;
int const p=3;

void input(int **a,int f, int k)
{
    int i,j;
    for(i=0;i<f;i++)
    {
        for(j=0;j<k;j++)
        {
            cin>>a[i][j];
        }
    }
}

int main()
{
    int *a1[m];
    for(int i = 0; i < m; i++)
        a1[i] = new int[n];
    input(a1,m,n);
}

but I am unable to understand why it is giving me error with a1[m][n]; as this is also declaring 2D array ?

Is there any way that I can use a1[m][n]; for declaring 2D array and passing it in function ?

463035818_is_not_a_number
  • 64,173
  • 8
  • 58
  • 126
Pankaj Sharma
  • 1,583
  • 1
  • 12
  • 37

1 Answers1

0

Your first version might be in C++

void input(int (&a)[m][n]);

but using std::array, you will have more intuitive syntax.

Jarod42
  • 173,454
  • 13
  • 146
  • 250
  • what If m,n are not global and want to take parameter as - `void input(int **a,m,n)` ? Is there any way to define array with `a1[m][n]` and passing it with double pointer ? – Pankaj Sharma May 25 '20 at 09:22
  • if `m` and `n` are compile-time constant, you can turn `input` as `template`. if `m` and `n` are runtime value, `std::vector` would be appropriate. `int [m][n]` and `int**` are really different type with different layout (even if they have similar syntax for indexing). – Jarod42 May 25 '20 at 09:26