我在声明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数组时它为何工作方式不同
您显示一个声明为的3D数组,permutazioni[variable][10][2]
但是当您尝试动态分配时,您切换了最后两个维度。
您可以执行以下操作:
#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的边界始终是一个好主意。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句