c语⾔⼆维数组new,如何使⽤new在C++中声明⼆维数组?
尚⽅宝剑之说
在C ++ 11中,它是可能的:auto array = new double[M][N]; 这样,内存不会被初始化。要初始化它,请执⾏以下操作:auto array = new double[M][N]();⽰例程序(使⽤“g ++ -std = c ++ 11”编译):#include #include #include #include #include using namespace std;int main(){ const auto M = 2; const auto N = 2; // allocate (no initializatoin) auto array = new
double[M][N]; // pollute the memory array[0][0] = 2; array[1][0] = 3; array[0][1] = 4; array[1][1] = 5; // re-allocate, probably will fetch the same memory block (not portable) delete[] array; array = new double[M][N]; // show that memory is not initialized for(int r = 0; r < M; r++) { for(int c = 0; c < N; c++) cout << array[r][c] << " "; cout << endl; } cout << endl; delete[] array; // the proper way to zero-initialize the array array = new double[M][N](); // show the memory is initialized for(int r = 0; r < M; r++) { for(int c = 0; c < N; c++) cout << array[r][c] << " "; cout << endl; } int info; cout << abi::__cxa_demangle(typeid(array).name(),0,0,&info) << endl; return 0;}输出:2
4 3
5 0 0 0 0 double (*) [2]c语言二维数组表示方法
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论