我是C ++的新手,正在尝试使用指向指针的指针构建3维数组。我确信这样做有更有效的方法,但是我现在正在尝试理解指针。作为示例代码,我最初有以下代码,可以很好地工作,分配,初始化和释放内存。void builder(int aSize1, int aSize2, int aSize3){ int i1, i2, i3; int ***frequencies; cout << "allocation started ..." << endl; frequencies = new int** [aSize1+1]; for (i1=0; i1<=aSize1; i1++){ frequencies[i1] = new int*[aSize2+1]; for (i2 = 0; i2 <= aSize2; i2++) { frequencies[i1][i2] = new int [aSize3 + 1]; } } cout << "allocation done" << endl; cout << " " << endl; cout << "before initialization" << endl; for (i1=0; i1<=aSize1; i1++){ for(i2=0; i2<=aSize2; i2++){ for(i3 = 0; i3 <= aSize3; i3++) { frequencies[i1][i2][i3]= (i1 * i2) % 10; } } } cout << "after initialization" << endl; cout << " " << endl; /* the "destroyer" part */ cout << "deleting ..." << endl; for (i1=0; i1<=aSize1; i1++){ for(i2=0; i2<=aSize2; i2++){ delete [] frequencies[i1][i2]; } } for (i1=0; i1<aSize1; i1++){ delete [] frequencies[i1]; } delete [] frequencies; cout << "deleting done" << endl;}我想通过将上面的代码分成几部分来提高赌注,以便可以在程序的main()函数中使用初始化的数组(只是看看是否也可以在其中访问它们)。所以,我最终做了以下事情头文件:void builder(int aSize1, int aSize2, int aSize3, int*** frequencies){ int i1, i2, i3; //int ***frequencies; cout << "allocation started ..." << endl; frequencies = new int** [aSize1+1]; for (i1=0; i1<=aSize1; i1++){ frequencies[i1] = new int*[aSize2+1]; for (i2 = 0; i2 <= aSize2; i2++) { frequencies[i1][i2] = new int [aSize3 + 1]; } } cout << "allocation done" << endl; cout << " " << endl; cout << "before initialization" << endl; for (i1=0; i1<=aSize1; i1++){ for(i2=0; i2<=aSize2; i2++){ for(i3 = 0; i3 <= aSize3; i3++) { frequencies[i1][i2][i3]= (i1 * i2) % 10; } } cout << **(frequencies[i1]+2) << endl; } cout << "after initialization" << endl; cout << " " << endl;}void destroyer( int aSize1, int aSize2, int aSize3, int*** frequencies ){ int i1, i2; cout << "deleting ..." << endl; for (i1=0; i1<=aSize1; i1++){ for(i2=0; i2<=aSize2; i2++){ delete [] frequencies[i1][i2]; } } for (i1=0; i1<aSize1; i1++){ delete [] frequencies[i1]; } delete [] frequencies; cout << "deleting done" << endl;}和我的main()试图不费吹灰之力地访问3d数组。int main(){ int aSize1 = 10; int aSize2 = 10; int aSize3 = 10; int*** freq; builder(aSize1, aSize2, aSize3, freq); cout << "builder finished" << endl; cout << **(freq[1]+2) << endl; destroyer( aSize1, aSize2, aSize3, freq);}当我对此进行编译时,“生成器”功能运行良好,但是每当我尝试访问main函数中的3d数组时,都会遇到分段错误。我希望它能奏效,因为我在书中已经读过,如果使用指向函数的指针通过引用传递了某些东西,则该函数将具有操纵它的能力。另外,我希望我需要将3d数组取消引用3次(即*** freq)才能正确访问元素,但是编译器因为尝试这样做而生气,并脱口而出 myBuilder.cpp:42:17:错误:间接需要指针操作数(“ int”无效) cout 我知道这是一个新问题,但是任何帮助将不胜感激! 最佳答案 frequencies和builder中的destroyer指针是freq中main指针的副本。因此,在builder中设置它不会更改main中的(未初始化)指针。您需要引用一个指针:void builder(int aSize1, int aSize2, int aSize3, int***& frequencies);并且对于您的间接级别,请注意,如果freq是int***,则freq[1]是int**。关于c++ - c++中使用指针的数组:访问返回的数组时出现段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40849750/ 10-11 18:34