gpt4 book ai didi

c++ - 打印 3D 指针数组的元素

转载 作者:太空宇宙 更新时间:2023-11-04 13:21:04 24 4
gpt4 key购买 nike

这是我的完整代码:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <stdio.h>
#include <string.h>

using namespace std;

int main(){

int ***my3DArray;
int length, width, height;

bool doAgain = true;
string answer("");
string yes("y");

do{
cout << "Enter length: ";
cin >> length;
cout << "\nEnter width: ";
cin >> width;
cout << "\nEnter height: ";
cin >> height;

srand((unsigned)time(NULL));

my3DArray = new int**[length];

for (int i= 0; i < length; ++i){

my3DArray[i] = new int*[width];

for(int j = 0; j< width; ++j){

my3DArray[i][j] = new int[height];

for(int k = 0; k < height; ++k){

my3DArray[i][j][k] = rand()%100;

cout << my3DArray[i][j][k] << " ";

do{
for (int i = 0; i < length; ++i){
for (int j = 0; j < width; ++j){
for (int k=0; k< height; k++){
cout << "\n\nEnter coodinates: ";
cin >> i;
cin >> j;
cin >> k;
cout << "Element is " << my3DArray[i][j][k];
}
cout << endl;
}
cout << endl;
}
cout << "Find another element? (Y/n)";

cin >> answer;

if(answer.compare(yes) == 0)
doAgain = true;

else doAgain = false;
}

while(doAgain == true);

}
cout << endl;

}
cout << endl;

}

for(int i = 0; i < length; i++){

for(int j = 0; j < width; j++){

delete[]my3DArray[i][j];

}

delete[]my3DArray[i];
}

delete[]my3DArray;

my3DArray = NULL;

cout << "Again? (y, n)";

cin >> answer;

if(answer.compare(yes) == 0)
doAgain = true;

else doAgain = false;

}

while(doAgain == true);

}

这会打印一个 3D 整数数组,我需要编写一个名为 tick 的函数来返回用户指定坐标 i j k 的元素。那部分代码是这样的

do{
for (int i = 0; i < length; ++i){
for (int j = 0; j < width; ++j){
for (int k=0; k< height; k++){
cout << "\n\nEnter coodinates: ";
cin >> i;
cin >> j;
cin >> k;
cout << "Element is " << my3DArray[i][j][k];
}
cout << endl;
}
cout << endl;
}
cout << "Find another element? (Y/n)";

cin >> answer;

if(answer.compare(yes) == 0)
doAgain = true;

else doAgain = false;
}

while(doAgain == true);

当我的代码中有这个时,它不会打印出 3D 数组,并且在它应该打印元素时出现段错误。有任何想法吗?提前致谢

最佳答案

当声明数组只是指向列表中第一项的指针时,请使用 int my3DArray[256][256] 而不是 int ***my3DArray。然后运行一个 for 循环来遍历该列表。

关于c++ - 打印 3D 指针数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35282674/

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