c语言二维数组new,如何使用new在C ++中声明二维数组?

991a124dfb10371e7a63f37fbe8b9a6d.png

尚方宝剑之说

在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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值