在 c++ 中初始化多维动态数组

Initializing multidimensional dynamical array in c++

本文关键字:动态 数组 初始化 c++      更新时间:2023-10-16

我在以 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 改进的。可能值得一试。