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

//二位数组参数传递

//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);//不能使用display4
	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;
}

  

posted @ 2019-02-03 10:59  xslwm  阅读(186)  评论(0编辑  收藏  举报