[英]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
它将运行清楚而没有任何问题。 没有任何问题,以及如果我声明数组permutazioni[variable][10][2]
具有相同的代码和任何值valide
。 我真的不知道问题可能是什么以及为什么在使用我之前提到的两个不同的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;
}
这里有一个生动的例子。
除此之外,检查用于访问数组元素的inddecs的边界始终是一个好主意。
如何使用这种语法? 尚未对3维数组进行全面测试,但我通常将这种样式用于2维数组。
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进行改进。 可能值得一试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.