将2D数组传递给函数

时间:2017-09-30 20:29:51

标签: c++ arrays function pointers

我是编程新手。

用户将输入2D数组的大小,然后我想将此数组传递给函数。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

有两种方法可以实现目标。

第一种方式使用动态分配的C风格数组。除非您被迫支持现有代码,否则不应该在C ++中执行此操作。但在这种情况下,最好考虑重构,也许。

第二种方式正在使用std::vector。该类用内存封装低级操作。它将使您摆脱许多潜在的错误。

为了向您展示std::vector的优点,我写了两个程序。他们输入2D数组的大小(换句话说,它被称为矩阵)并创建它。

使用C风格的数组创建矩阵需要使用指针进行大量代码和操作。 为简单起见,以下代码不处理异常。在实际代码中,您应该这样做以避免内存泄漏,但代码会变得更难。

#include <iostream>
#include <cstddef>

using namespace std;

void function(int** matrix, size_t nrows, size_t ncols)
{

}

int main()
{
    size_t nrows;
    size_t ncols;

    cin >> nrows >> ncols;

    // allocate memory for matrix
    int** matrix = new int*[nrows];
    for (size_t i = 0; i < nrows; ++i)
        matrix[i] = new int[ncols];

    function(matrix, nrows, ncols);

    // release memory
    for (size_t i = 0; i < nrows; ++i)
        delete[] matrix[i];
    delete[] matrix;
}

因此在C ++中使用std::vector会更容易。由于std::vector是一个类,它有构造函数和析构函数封装分配和释放内存。

#include <iostream>
#include <vector>

using namespace std;

void function(vector<vector<int>>& matrix)
{

}

int main()
{
    size_t nrows;
    size_t ncols;

    cin >> nrows >> ncols;

    // create matrix
    vector<vector<int>> matrix(nrows);
    for (size_t i = 0; i < nrows; ++i)
        matrix[i] = vector<int>(ncols);

    // you don't even need to pass sizes of matrix
    function(matrix);

    // automatically called destructor of matrix releases memory
}
相关问题