如何创建一个具有可变行且每行有 3 列的 2D 数组?
How to create a 2D array with variable row and each row has 3 columns?
我在想:
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
}
相关文章:
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 四边形的 2D 旋转
- 打印第二列时的2d字符矢量打印空间
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 从我的2d数组中的一列返回的字符串值被压缩为一个字符串(在Mac os上打开Windows txt文件)
- 如何创建一个具有可变行且每行有 3 列的 2D 数组?
- 在MPI中发送动态分配的2D数组的列
- 如何将列附加到现代C 中的2D向量
- 将添加的列初始化为可调整大小的 2D 向量
- 当我传递带有列大小的2D数组时,它会显示出一些错误
- C++ 如何从.dat文件构建字符串的 2D 矩阵?5 列 x 行
- 2D(每列的最大值)
- 请求想法 - 如何对具有多行和 3 列的 2d 数组进行排序,维护数据行
- 如何使用object.get()将文本读取到一个参数比文本大的2D数组中(2D数组有更多的行和列)
- 搜索作为行和列的m/n的2D阵列中的元素
- 在c中的2d数组的末尾添加额外的数据列
- c++从文本文件中读取3列到2D数组或3个单独的数组中
- 将行和列大小未知的2d-Array传递给函数(c++)
- 如何更改 2d C++数组的用户输入行和列的值
- 如何在 c++ 中从现有 2D 向量创建具有特定列的新向量