打印3D指针数组元素

时间:2016-02-09 01:54:15

标签: c++ arrays multidimensional-array function-pointers

这是我的完整代码:

#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数组,并且当它打算打印元素时我会遇到分段错误。有任何想法吗?提前致谢

1 个答案:

答案 0 :(得分:0)

声明数组时,

而不是int ***my3DArray使用int my3DArray[256][256]只是指向列表中第一项的指针。然后运行for循环以浏览该列表。