gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:50:24 24 4
gpt4 key购买 nike

我在声明 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;
}

一个活生生的例子 here .

除此之外,检查用于访问数组元素的 inddec 的边界始终是个好主意。

关于c++ - 在 C++ 中初始化多维动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35379566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com