如何在不使用指针的情况下将动态2D数组传递给函数? [英] how to pass dynamic 2d array to a function without using the pointers?

查看:85
本文介绍了如何在不使用指针的情况下将动态2D数组传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了这个,但是没有用! 有人可以帮我吗,这很重要:(

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)

导致

#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);
}

,但是您可能更喜欢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);
}

这篇关于如何在不使用指针的情况下将动态2D数组传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆