C语言描述:
#include "stdio.h"
#include "stdlib.h"
#include "assert.h"
//二维数组内存申请
int** createArray2D(int row, int clos)
{
int** pArray = (int**)malloc(sizeof(int*) * row);
assert(pArray);
for (int i = 0; i < row; i++)
{
pArray[i] = (int*)malloc(sizeof(int) * clos);
}
return pArray;
}
//二维数组初始化
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 deleteMemory(int**& pArray, int row)
{
for (int i = 0; i < row; i++)
{
free(pArray[i]);
}
free(pArray);
pArray = NULL;
if (pArray == NULL)
{
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 = createArray2D(4, 3);
InitArray(pArray, 4, 3);
PrintfArray(pArray, 4, 3);
deleteMemory(pArray,4);
//2.数组指针申请内存
printf("数组指针申请内存:\n");
int(*p)[3] = NULL;
p = (int(*)[3])malloc(sizeof(int[3]) * 4);
InitArray1(p, 4, 3);
PrintfArray1(p, 4, 3);
system("pause");
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;
}
运行结果:
标签:int,pArray,cols,C++,++,动态内存,Array,指针,row From: https://www.cnblogs.com/zhuchunlin/p/18349000