二位数组传参及二位数组动态分配问题

Posted xslwm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二位数组传参及二位数组动态分配问题相关的知识,希望对你有一定的参考价值。

//二位数组参数传递

//1.
void display1(int arr[][4], const int rows)
{
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			cout << arr[i][j] << ‘ ‘;
		}
		cout << endl;
	}
	cout << endl;
}

//2.
void display2(int(*parr)[4], const int rows)
{
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			cout << parr[i][j] << ‘ ‘;
		}
		cout << endl;
	}
	cout << endl;
}
//parr[i]等价于*(parr+i)


//3.
void display3(int **parr, const int rows, const int cols)
{
	for (int i = 0; i < rows; ++i)
	{
		for (int j = 0; j < cols; ++j)
		{
			cout << *((int*)parr + i * cols + j) << " ";   //注意:(parr+i*cols+j), 不是(arr+i*rows+j), 不能使用parr[i][j]
		}
		cout << endl;
	}
	cout << endl;
}

void display4(int **parr, const int rows, const int cols)
{
	for (int i = 0; i < rows; ++i)
	{
		for (int j = 0; j < cols; ++j)
		{
			cout << parr[i][j] << " ";
		}
		cout << endl;
	}
	cout << endl;
}

int main()
{
	int rows = 3;
	int cols = 4;

	int arr[][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 }; 

	display3((int**)arr, rows, cols);
	cout << "=======" << endl;

	//动态二位数组
	int **p;
	p = new int*[rows];//创建行指针
	for (int i = 0; i < rows; ++i)
	{
		p[i] = new int[cols]; //为每一行分配空间
	}

	for (int i = 0; i < rows; ++i)
		for (int j = 0; j < cols; ++j)
			p[i][j] = i * cols + j;

	display4(p, rows, cols);

	//删除行数组空间
	for (int i = 0; i < rows; ++i)
		delete[] p[i];

	//删除行指针
	delete[] p;
	p = nullptr;


	//一次性分配空间
	int **p1;
	p1 = new int*[rows];
	p1[0] = new int[rows*cols];
	for (int i = 0; i < rows; ++i)
		p1[i] = p1[0] + cols*i;

	for (int i = 0; i < rows; ++i)
		for (int j = 0; j < cols; ++j)
			p1[i][j] = i * cols + j;// 或者    *(p1[0]+i*cols+j) = i * cols + j;
			

	display4(p1, rows, cols);

	display3((int**)p1[0], rows, cols);


	delete[] p1[0];
	delete[] p1;
}

  

以上是关于二位数组传参及二位数组动态分配问题的主要内容,如果未能解决你的问题,请参考以下文章

vue 路由传参及解决动态路由传参刷新会消失问题

在Jmeter中设置全局变量,实现跨线程组传参

------ 比较二位数组大小-----

2019.12.10 二位数组

二位数组按行按列遍历效率问题小细节

二位数组按行按列遍历效率问题小细节