您的位置:首页 > 编程语言 > C语言/C++

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

2017-03-03 23:30 288 查看
// 动态创建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;
        }
     
a0cc
  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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C C++ 释放 数组 创建