您的位置:首页 > 其它

关于数组做函数参数的问题汇总

2013-04-20 13:27 281 查看
首先是数组元素作为函数的实参,这和直接用多个变量作为函数的实参在用法上没有什么差别。

作为例子的代码:

#include<iostream>
using namespace std;
int main(){
int max(int a,int b);
int a[2],m;
a[0]=1;
a[1]=2;
m=max(a[0],a[1]);
cout<<m;
return 0;
}
int max(int a,int b ){
if(a<b)a=b;
return a;
}


输出结果是:2

然后,是用数组名作为函数参数,数组名其实代表的是数组首个元素的指针。

#include<iostream>
using namespace std;
int main(){
void alter(int b[]);//b[]括号里面的数值可写可不写,其作用是使编译系统把它当作一维数组来处理
int a[2];
a[0]=1;
a[1]=2;
alter(a);
cout<<a[0]<<"\n";
cout<<a[1]<<"\n";
return 0;
}
void alter(int b[]){
b[0]=3;
b[1]=4;
}
输出结果是:

3

4

如果我们这样写:

#include<iostream>
using namespace std;
int main(){
void alter(int b[20]);//b[]括号里面的数值可写可不写,其作用是使编译系统把它当作一维数组来处理
int a[2];
a[0]=1;
a[1]=2;
alter(a);
cout<<sizeof(a);
return 0;
}
void alter(int b[20]){
cout<<sizeof(b)<<endl;
}


输出结果:

4

8

为什么我们已经定义了a[2]并且还赋值了,传递到函数以后,大小就只有一个单位呢?

其实,我们定义b[ ]或者b[2]或则b[1]、b[20]、b[100],作用都相当于是 *b。编译器直接忽略了,括号里面的数值。

为了能够更高的说明,数组名作为实参实际上是传递的数组的首指针,可以再看一下这个例子:

#include<iostream>
using namespace std;
int main(){
void alter(int *b);
int a[2];
a[0]=1;
a[1]=2;
alter(a);
cout<<a[0]<<"\n";
cout<<a[1]<<"\n";
return 0;
}
void alter(int *b){
*b=3;
*(b+1)=4;
}


这个和上面的那个输出结果完全一样!

================================分割线==========================

接下来,总结一下,数组的引用相关问题

首先是一个普通变量作为数组中一个值的引用的例子:

#include<iostream>
using namespace std;
int main(){
int a[2];
a[0]=1;
a[1]=2;
int &t=a[0];
t=5;
cout<<a[0]<<"\n";
return 0;
}


输出结果是:5

普通变量作为数组中一个值的引用时,在使用上和int &a=b;并没有什么区别。

我们很自然的想到,普通的变量可以作为数组元素的引用,那么数组元素可否作为其他元素的引用呢?

看下面的代码:

#include<iostream>
using namespace std;
int main(){
int a[2];
int b=100;
&a[0]=b;//这么做是不被允许的
cout<<a[0]<<endl;
return 0;
}
编译器报错了,提示我们这样做是不被允许的。

但是捏,一个数组整体可以作为另一个数组的引用:

#include<iostream>
using namespace std;
int main(){
int a[2];
a[0]=1;
a[1]=2;
int (&b)[2]=a;
b[0]=3;
b[1]=4;
cout<<a[0]<<endl;
cout<<a[1]<<endl;
return 0;
}


#include<iostream>
using namespace std;
int main(){
int a[2];
a[0]=1;
a[1]=2;
int (&b)[2]=a;
b[0]=3;
b[1]=4;
cout<<a[0]<<endl;
cout<<a[1]<<endl;
return 0;
}


因为数值中的元素是不可以其他变量的引用的额,所以需要用(&b)来说明,这是数组整体引用,然后还必须写清楚数组的大小,即:

(int (&b)[2])


这个使用方法,也就引出了,数组作为函数的形参的使用方法。

我们再看数组作为函数的形参的时候应该是怎样的。

#include<iostream>
using namespace std;
int main(){
void sm(int (&b)[2]);
int a[2];
a[0]=1;
a[1]=2;
sm(a);
cout<<a[0]<<endl;
cout<<a[1]<<endl;
return 0;
}
void sm(int (&b)[2]){
b[0]=3;
b[1]=4;
}
输出结果是

3

4

#include<iostream>
using namespace std;
int main(){
int a[2];
a[0]=1;
a[1]=2;
int (&b)[2]=a;
b[0]=3;
b[1]=4;
cout<<a[0]<<endl;
cout<<a[1]<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: