C++ - 二級指標動態記憶體申請與釋放

[BORUTO]發表於2024-08-08

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++ - 二級指標動態記憶體申請與釋放

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;
}

執行結果:

C++ - 二級指標動態記憶體申請與釋放

相關文章