C ++尝试使用函数参数定义2D数组

时间:2018-12-18 16:28:55

标签: c++ arrays arguments 2d constants

我要定义一个二维字符数组,在该数组中,我传递给保存该数组的函数的参数将用于确定数组每个维度的大小。

int func(const int x, const int y) {

    char maze[x][y] = { 0 };
    return 0; 
}

当在函数内部将x&y定义为常量整数时,就很好地定义了数组。当x和y是函数的参数时,程序将不会编译。为什么会这样,我该如何解决?

3 个答案:

答案 0 :(得分:2)

您可以像这样围绕一维数组制作包装器:

class Maze {
    friend class Row;
public:
    /* This helper class represents a single row of the maze */
    class Row {
        friend class Maze;
        Maze& owner;
        std::size_t row;
        Row(Maze& owner_, std::size_t row_) : owner(owner_), row(row_) {}
        /* this operator resolves 2nd pair of brackets */
    public:
        inline char& operator[](std::size_t col) { return owner.data[col + row*owner.cols]; }
    };
    Maze(std::size_t rows_, std::size_t cols_)
      : data(rows_ * cols_, 0)
      , cols(cols_)
    {}
    /* this operator resolves 1st pair of brackets */
    inline Row operator[](std::size_t index) { return Row(*this, index); }
private:
    std::vector<char> data;
    std::size_t cols;
};

...

Maze m(5, 10);
m[2][3] = 1;

答案 1 :(得分:0)

您需要使用动态内存分配。可变长度数组不是c ++标准的一部分。但是可变参数长度数组可作为GCC的扩展。尽管您可以使用STL或实现您的类,但不要忘记new []和二维数组的一维表示形式:

char* maze = new char[x*y]; // create
maze[i + j * x]; // access
delete[] maze; // delete

它紧凑且在大多数情况下很快。

答案 2 :(得分:0)

  

在函数内部将x和y定义为常量整数时,数组定义得很好

之所以能够工作,是因为数组的大小是由编译器定义并知道的,并且在编译时

  

当x和y是该函数的参数时,程序将不会编译。

当您只想在调用函数时调用数组时,您可以要求程序在运行时期间执行此操作。 。正如Dmytro Dadyka回答的那样,您必须使用动态内存分配并管理自己的内存释放(delete []迷宫; //删除)

这是使用 template 动态定义2D数组的替代方案!请注意,它总是在编译时完成。

template<int X, int Y>
int f()
{
    char c[X][Y];

    for(int x=0; x < X; ++x)
    {
        for(int y=0; y < Y; ++y)
        {
            c[x][y] = '1';
        }


    }
    // write your algorithm now!....
    c[2][2] = 'a';

    for(int x=0; x < X; ++x)
    {
        for(int y=0; y < Y; ++y)
        {
           std::cout << c[x][y] << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}

    int main()
    {
      f<5,5>();
      f<7,4>();
      return 0;
    }