C/C++中动态创建和释放二维数组的两种办法

// 动态创建nRow*nCol大小的二维数组,并初始化所有项为0
void MatrixConstruct(double ***pMatrix, int nRow, int nCol)
{
        // 分配所有行的首地址  
        *pMatrix = (double **)malloc(sizeof(double *) * nRow); 
        for (int i = 0; i < nRow; i++)
        { // 按行分配每一列  
                (*pMatrix)[i] = (double *)malloc(sizeof(double) * nCol);
                memset((*pMatrix)[i],0, sizeof(double) * nCol);
        }
}


// 动态创建nRow*nCol大小的二维数组,并初始化所有项为0
double** MatrixConstruct(int nRow, int nCol)
{
        double** matrix = NULL;
        // 分配所有行的首地址  
        matrix = (double **)malloc(sizeof(double *) * nRow);
        for (int i = 0; i < nRow; i++)
        { // 按行分配每一列  
                matrix[i] = (double *)malloc(sizeof(double) * nCol);
                memset(matrix[i], 0, sizeof(double) * nCol);
        }
        return matrix;
}


// 释放动态创建的nRow行的二维数组空间
void MatrixDestroy(double **pMatrix, int nRow)
{
        for (int i = 0; i < nRow; i++)
        {
                free((pMatrix)[i]);
                pMatrix[i] = NULL;
        }
        free(pMatrix);
}


int main()
{
        int nRow = 10, nCol = 4;
        double **matrix1 = MatrixConstruct(nRow, nCol);
        MatrixDestroy(matrix1, nRow);
        matrix1 = NULL;


        double **matrix2 = NULL;
        MatrixConstruct(&matrix2,nRow, nCol);
        MatrixDestroy(matrix2, nRow);
        matrix2 = NULL;
        return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值