3D 指针数组的打印元素

Printing Elements of 3D Array of pointers

本文关键字:打印 元素 数组 指针 3D      更新时间:2023-10-16

这是我的完整代码:

#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 << "nnEnter 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 << "nnEnter 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声明数组时使用int my3DArray[256][256]只是指向列表中第一项的指针。 然后运行 for 循环来浏览该列表。