如何创建一个具有可变行且每行有 3 列的 2D 数组?

How to create a 2D array with variable row and each row has 3 columns?

本文关键字:列的 2D 数组 何创建 创建 一个      更新时间:2023-10-16

我在想:

int i,z[3];
int q[i][z[3]];

这个声明是正确的吗?

如果没有,这建议一种我可以存储i行的方法,每行都有 3 个整数。

C 支持可变长度数组,其中数组尺寸在运行时确定。

您对q的定义是有效的,第一个维度的大小i,第二个维度的大小z[3]。 但是,由于z是一个大小为 3 的数组,因此其有效索引为 0 - 2,因此表达式z[3]读取数组末尾,调用未定义的行为。

如果希望第二个维度的大小为 3,只需指定该大小即可。

int q[i][3];

@dbush在他关于可变长度数组(VLA(的回答中已经提到过

这个答案将提供另一种选择。

您可以使用std::vector来实现它:

std::vector<std::vector<int>> vec2d; // 2D vector
int row = 2; // row is variable
for (int i = 0; i < row; i++) {
vec2d.push_back(std::vector<int>(3)); // each row has 3 columns
}
// just for checking the size
for (auto const& v: vec2d) {
std::cout << v.size() << " "; // 3 3
// ^ ^ each row has 3 columns
}