函数参数传递二维数组

今天写个小程序,发现对二维数组作为函数参数传递的情况不够清楚,故写测试程序如下。(基本功很重要,还远远不够扎实啊,难过)

refer:参数传递二维数组

二维数组作为参数传递问题


#include <iostream>

using namespace std;

//数组名形式,第一维可省,第二维必须有,否则无法通过编译
void func1( int arr[][3], int nRows, int nCols ){
	for ( int i=0; i<nRows; ++i){
		for ( int j=0; j<nCols; ++j ){
			cout<<arr[i][j];
		}
		cout<<endl;
	}
	cout<<"func1 is done";
}

//二维数组引用形式,必须同时指定一二维大小
void func2( int (&arr)[2][3], int nRows, int nCols ){
	for ( int i=0; i<nRows; ++i){
		for ( int j=0; j<nCols; ++j ){
			cout<<arr[i][j];
		}
		cout<<endl;
	}
	cout<<"func2 is done";
}

//二维数组指针形式,必须同时指定一二维大小
void func3( int (*arr)[2][3], int nRows, int nCols ){
	for ( int i=0; i<nRows; ++i){
		for ( int j=0; j<nCols; ++j ){
			cout<<(*arr)[i][j];	//先对指针解引用,再当做数组名用
		}
		cout<<endl;
	}
	cout<<"func3 is done";
}

//数组指针作为形参,本质是指向第二维数组的指针,故必须指定二维大小;否则编译通过,但无法调用
void func4( int (*arr)[3], int nRows, int nCols ){
	for ( int i=0; i<nRows; ++i){
		for ( int j=0; j<nCols; ++j ){
			cout<<arr[i][j];
		}
		cout<<endl;
	}
	cout<<"func4 is done";
}

//指针形式,调用本函数时,实参要转换为对应指针类型再来调用;无论几维,都看作指针
void func5( int *arr, int nRows, int nCols ){
	for ( int i=0; i<nRows; ++i){
		for ( int j=0; j<nCols; ++j ){
			cout<<*(arr+i*i+j);	//注意这里!先寻址再解引用
		}
		cout<<endl;
	}
	cout<<"func5 is done";
}

//多重指针形式,调用本函数时,实参本质不应该是数组,而是指针,即数组是动态生成的
void func6( int **arr, int nRows, int nCols ){
	for ( int i=0; i<nRows; ++i){
		for ( int j=0; j<nCols; ++j ){
			cout<<arr[i][j];	//注意这里!先寻址再解引用
		}
		cout<<endl;
	}
	cout<<"func6 is done";
}

//对一维数组来说,可以直接用数组名为实参、一重指针为形参来调用
void _1Dfunc( int *arr, int len ){
	for ( int i=0; i<len; ++i){
		cout<<arr[i];
	}
	cout<<endl;
	cout<<"_1Dfunc is done";
}

int main(){
	//int arr[3][3] = {0};
	//for ( int i=0; i<3; ++i){
	//	for ( int j=0; j<3; ++j ){
	//		arr[i][j] = i*j+j;
	//	}
	//}
	int arr[2][3]={{1,2,3},{4,5,6}};
	func1(arr, 2, 3);
	cout<<endl;
	func2(arr, 2, 3);
	cout<<endl;
	func3(&arr, 2, 3);	//调的是二维数组指针形式,用地址为实参
	cout<<endl;
	func4(arr, 2, 3);
	cout<<endl;
	//func5 不知是否足够合理,可通过,但暂时少用
	func5((int *)arr, 2, 3);	//arr是二维数组名,强制转换;arr本身是指向数组的指针,这里转换为int指针;
	cout<<endl;

	int nRows = 2, nCols = 3;
	int **arr2 = new int*[nRows];
	for ( int i=0; i<nRows; ++i ){
		arr2[i] = new int[nCols];
		for ( int j=0; j<nCols; ++j ){
			arr2[i][j] = i*nCols+j+1;
		}
	}
	func6(arr2, 2, 3);
	cout<<endl;

	int arr1D[3] = {1,2,3};
	_1Dfunc(arr1D,3);
	cout<<endl;

	system("pause");
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值