简体   繁体   中英

how to pass dynamic 2d array to a function without using the pointers?

I tried this but it is not working ! can any one help me please this is very important :(

#include <iostream>
using namespace std;
int a[100][100];

void read(int a[][100],int n)
{
  int i,j;
  for(i=0;i<n;i++)
       for(j=0;j<n;j++)
     cin>>a[i][j];
}

int main ()
{
    int n;
    cin>>n;
    int a[n][n];
   read(a,n);
}

The unclear syntax to pass array by reference is:

void read(int (&a)[100][100], int n)

resulting in

#include <iostream>

void read(int (&a)[100][100], int n)
{
  for(int i = 0; i < n; i++)
       for(int j = 0; j < n; j++)
           std::cin >> a[i][j];
}

int main ()
{
    int n;
    std::cin >> n;
    int a[100][100];
    read(a, n);
}

but you might prefer std::vector :

#include <iostream>
#include <vector>

void read(std::vector<std::vector<int>> &mat)
{
    for (auto& v : mat) {
        for (auto& e : v) {
            std::cin >> e;
        }
    }
}

int main ()
{
    int n;
    std::cin >> n;
    std::vector<std::vector<int>> mat(n, std::vector<int>(n));
    read(mat);
}

Since this is tagged C++. I'd like to suggest usage of std::vector . It's dynamic container which is very useful. You can resize it, clear it fill it with ease. Once you understand it's basic usage, they would come really handy in your future C++ development. I modified your code slightly:

#include <iostream>
#include <vector>
using namespace std;

void read(vector<vector<int> >& arr,int n)
{
  int i,j;
  for(i=0;i<n;i++)
       for(j=0;j<n;j++)
           cin>>arr[i][j];
}
int main ()
{
    int N;
    cin>>N;
    vector<vector<int> > arr(N, vector<int>(N));
    read(arr, N);
}

They have many advantages over the primitive arrays like they can be initialized easily, suppose you want to initialize all to zero :

vector<vector<int> > arr(N, vector<int>(N, 0));

You don't have to worry about adding the array size whenever passing in functions. vector can easily handle this:

for(i = 0; i < arr.size(); i++) {
  for(j = 0; j < arr[i].size(); j++) {
    // do stuff
  }
}

Moreover with the added methods of the Standard template library like fill , swap . Many operations can be handled easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM