在 c++ 中初始化多维动态数组
Initializing multidimensional dynamical array in c++
我在以 c 样式声明多维动态数组时遇到问题。我想动态声明一个像permutazioni[variable][2][10]
这样的数组,我使用的代码如下(carte
是我定义的类):
#include "carte.h"
//other code that works
int valide;
carte *** permutazioni=new carte**[valide];
for (int i=0; i<valide; i++){
permutazioni[i]=new carte*[2];
for (int j=0; j<2; j++) permutazioni[i][j]=new carte[10];
}
问题是,每当我取valide=2
或小于 2 时,代码就会在最后for (int i=0; i<valide; i++)
迭代中停止,但如果我采用valide=3
它就会运行干净,没有任何问题。如果我使用相同的代码和 valide
的任何值声明数组permutazioni[variable][10][2]
也没有问题。我真的不知道问题可能是什么,以及为什么在使用我之前提到的两个不同的 3d 数组时它的工作方式不同
您显示一个声明为 permutazioni[variable][10][2]
的 3D 数组,但当您尝试动态分配时,您切换了最后两个维度。
你可以做这样的事情:
#include <iostream>
#define NVAL 3
#define DIM_2 10 // use some more meaningfull name
#define DIM_3 2
// assuming something like
struct Card {
int suit;
int val;
};
int main() {
// You are comparing a 3D array declared like this:
Card permutations[NVAL][DIM_2][DIM_3];
// with a dynamical allocated one
int valid = NVAL;
Card ***perm = new Card**[valid];
// congrats, you are a 3 star programmer and you are about to become a 4...
for ( int i = 0; i < valid; i++ ){
perm[i] = new Card*[DIM_2];
// you inverted this ^^^ dimension with the inner one
for (int j = 0; j < DIM_2; j++)
// same value ^^^^^
perm[i][j] = new Card[DIM_3];
// inner dimension ^^^^^
}
// don't forget to initialize the data and to delete them
return 0;
}
这里有一个活生生的例子。
除此之外,检查用于访问数组元素的inddec的边界总是一个好主意。
使用这种语法怎么样?还没有对三维数组进行全面测试,但我通常将这种风格用于二维数组。
int variable = 30;
int (*three_dimension_array)[2][10] = new int[variable][2][10];
for(int c = 0; c < variable; c++) {
for(int x = 0; x < 2; x++) {
for(int i = 0; i < 10; i++) {
three_dimension_array[c][x][i] = i * x * c;
}
}
}
delete [] three_dimension_array;
显然,这可以是 c++ 11/14 改进的。可能值得一试。
相关文章:
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 输出没有重复元素的动态数组(收缩数组)C++
- 正在插入动态数组
- 如何在动态数组上使用搜索函数
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 静态数组的自由动态数组
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- 为什么 c++ 动态数组的大小没有改变?
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 指针的 C++ 动态数组 - 何时需要使用它?
- 删除动态数组时未定义标识符
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 动态数组的 C++ 重载加运算符
- 基于数组的列表 - 动态数组创建时出错