CPP在堆中生成二维数组的两种方式

别人的实现方式:关于使用C/C++在堆上开辟数组(一维数组和二维数组)

c++在堆区中创建数组的一些注意事项

演示代码

#include<cstdio>
#include <iostream>
using namespace std;

//堆中二维数组的两种方式
int main()
{
    
    
	//连续空间
	cout << "===连续空间===" << endl;
	int size = 2;
	int(* arr1)[3] = new int[size][3]{
    
     {
    
    1,2,3},{
    
    4,5,6} };
	for (int i = 0; i < size; i++)
	{
    
    
		for (auto a : arr1[i])
		{
    
    
			cout << a << "-";
		}
		cout << endl;
	}

	delete []arr1;
	arr1 = nullptr;


	//指针数组
	//假如是一幅图像
	/*
	1 2 3 0
	2 4 6 0
	3 6 9 0
	*/
	cout << "===指针数组===" << endl;
	int width = 4, height = 3;
	int** arr2 = new int* [height] {
    
    0};

	for (int i = 0; i < height; i++) {
    
    
		arr2[i] = new int[width] {
    
    1 * (i+1), 2 * (i + 1), 3 * (i + 1) };
	}

	for (int i = 0; i < height; i++) {
    
    
		for (int j = 0; j < width; j++) {
    
    
			cout << arr2[i][j] << " ";
		}
		cout << endl;
	}

	for (int i = 0; i < height; i++)
		delete[] arr2[i];
	delete[] arr2;
	arr2 = nullptr;

	return 0;
}

运行结果

===连续空间===
1-2-3-
4-5-6-
===指针数组===
1 2 3 0
2 4 6 0
3 6 9 0

猜你喜欢

转载自blog.csdn.net/haojie_duan/article/details/126773312