C语言描述:
#include "stdio.h"
#include "stdlib.h"
#include "assert.h"void InitArray(int** Array, int row, int cols)
{for (int i = 0; i < row; i++){for (int j = 0; j < cols; j++){Array[i][j] = i + j;}}
}
void PrintfArray(int** Array, int row, int cols)
{for (int i = 0; i < row; i++){for (int j = 0; j < cols; j++){printf("%d\t", Array[i][j]);}printf("\n");}
}void InitArray1(int Array[][3], int row, int cols)
{for (int i = 0; i < row; i++){for (int j = 0; j < cols; j++){Array[i][j] = i + j;}}
}void PrintfArray1(int Array[][3], int row, int cols)
{for (int i = 0; i < row; i++){for (int j = 0; j < cols; j++){printf("%d\t", Array[i][j]);}printf("\n");}
}int main()
{//1.二级指针申请内存printf("二级指针申请内存:\n");int** pArray = (int**)malloc(sizeof(int*) * 4);assert(pArray);for (int i = 0; i < 4; i++){pArray[i] = (int*)malloc(sizeof(int) * 3);}InitArray(pArray, 4, 3);PrintfArray(pArray, 4, 3);for (int i = 0; i < 4; i++){free(pArray[i]);}free(pArray);pArray = NULL;//2.数组指针申请内存printf("数组指针申请内存:\n");int(*p)[3] = NULL;p = (int(*)[3])malloc(sizeof(int[3]) * 4);InitArray1(p, 4, 3);PrintfArray1(p, 4, 3);return 0;
}
运行结果:
C++描述:
#include"iostream"
using namespace std;//二维数组内存申请
int** createArray2D(int row, int clos)
{int** pArray = new int* [row];for (int i = 0; i < row; i++){pArray[i] = new int[clos];}return pArray;
}//二维数组内存释放
void deleteMemory(int**& pArray, int row)
{for (int i = 0; i < row; i++){delete[] pArray[i];}delete[] pArray;pArray = nullptr;
}int main()
{int** p1 = createArray2D(3, 2);//初始化二维数组for (int i = 0; i < 3; i++){for (int j = 0; j < 2; j++){p1[i][j] = i;cout << p1[i][j] << "\t";}cout << endl;}deleteMemory(p1, 3);if (p1 == nullptr){cout << "释放成功" << endl;}return 0;
}
运行结果: