0

I am trying to pass a 2D array to a function but I am failing to do so. There is no problem with passing 1D array. How can I do this?

    #include <iostream>

using namespace std;

void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
        for (int j = 0; j < n; j++)
        {
                cout << matrix[j];
        }
}

int main()
{
    int n,m;
    cin>>n;
    //int matrix[n]={};
    DisplayBoard(matrix,n);
    return 0;
}
JustSoniBG
  • 29
  • 4

2 Answers2

0

i think you want to input index number (n) from user and then input array object from user too
i complete your code like this :

#include <iostream>
using namespace std;

void DisplayBoard(int matrix[],int n) // Prints out the given array.
{ 
  cout<<endl ; 
     for (int j = 0; j < n; j++)
      {
              cout << matrix[j]<<" ";
       }
    }

     int main() {
       int n,m;
         cin>>n ; 
         int matrix[n];
  
         for(int i=0;i<n;i++) {
            cin>>matrix[i];
               } 
             DisplayBoard(matrix,n);
          return 0;
        }

remember to declare array in main function too , that was one of your code error !

and this is incorrect to declare array :

int matrix[n]={} // incorrect !
Nima
  • 28
  • 8
0
Well. int matrix[n]={}; fills it with zeros and that's what I wanted to do. And my code with 1D array works fine but if I do it like so it does not.

    #include <iostream>

using namespace std;

void DisplayMatrix(int matrix[][],int n,int m)
{
    for(int i=0;i<n;i++)
    {
        for (int j = 0; j < m; j++)
        {
                cout << matrix[j];
        }
    }
}

int main()
{
    int n,m;
    cin>>n>>m;
    int matrix[n][m]={};
    DisplayMatrix(matrix,n,m);
    return 0;
}
JustSoniBG
  • 29
  • 4