C++用指针变量作为函数的参数接受数组的值的问题的总结
实参 | 形参 | 实例 |
---|---|---|
数组名 | 数组名 | 1.1 |
数组名 | 指针变量 | 1.2 |
指针变量 | 数组名 | 1.3 |
指针变量 | 指针变量 | 1.4 |
本文以输入10个整数,然后对其进行排序,然后输出的程序为例:
形参为数组名,实参是数组名
实例代码1.1:
#include<iostream> using namespace std; int main(){ void Sort(int a[],int n); int a[10],i; cout<<"Please input 10 interges: "<<endl; for(i=0;i<10;i++){ cin>>a[i]; } Sort(a,10); cout<<"Sorted order:"; for(i=0;i<10;i++){ cout<<a[i]<<" "; } cout<<endl; return 0; } void Sort(int a[], int n){ int i,j,k,tool; for(i=0;i<n;i++){ k=i; for(j=i;j<n;j++){ if(a[j]<a[k]) k=j; } tool=a[k]; a[k]=a[i]; a[i]=tool; } }
形参中a[ ]中,可以不写任何的数字,只需要表示这是一个数组即可。如果其中放数字的话,可以放置任何一个正整数(不一定等于实参数组的大小,可以比实参中的数组大或者小)。
即:
void Sort(int a[], int n )
也可以写成
void Sort(int a[2], int n)
或者
void Sort(int a[12], int n)
实参是数组名,形参是指针变量
实例代码1.2:
#include<iostream> using namespace std; int main(){ void Sort(int a[],int n); int a[10],i; cout<<"Please input 10 interges: "<<endl; for(i=0;i<10;i++){ cin>>a[i]; } Sort(a,10); cout<<"Sorted order:"; for(i=0;i<10;i++){ cout<<a[i]<<" "; } cout<<endl; return 0; } void Sort(int *a, int n){ int i,j,k,tool; for(i=0;i<n;i++){ k=i; for(j=i;j<n;j++){ if(a[j]<a[k]) k=j; } tool=a[k]; a[k]=a[i]; a[i]=tool; } }在文章《C++一维数组和指针的关系总结》中,已经提到数组名实际上代表数组的首元素的地址也就是说a等价于&a[0]
在实参中,数组名代表数组中的第一个元素的地址,所以实参实际上只传递了数组的第一个元素的指针。因此,在形参中,只需要一个指针变量来接受传递过来的值即可。
实参是指针变量,形参是数组
实例代码1.3:#include<iostream> using namespace std; int main(){ void Sort(int a[],int n); int a[10],i; cout<<"Please input 10 interges: "<<endl; for(i=0;i<10;i++){ cin>>a[i]; } Sort(&a[0],10); cout<<"Sorted order:"; for(i=0;i<10;i++){ cout<<a[i]<<" "; } cout<<endl; return 0; } void Sort(int a[], int n){ int i,j,k,tool; for(i=0;i<n;i++){ k=i; for(j=i;j<n;j++){ if(a[j]<a[k]) k=j; } tool=a[k]; a[k]=a[i]; a[i]=tool; } }
跟上文分析的一致,通过&a[0]作为实参进行传值,证明了数组名实际上代表数组的首元素的地址也就是说a等价于&a[0]
形参是指针变量,实参是指针变量
实例代码1.4:#include<iostream> using namespace std; int main(){ void Sort(int a[],int n); int a[10],i; cout<<"Please input 10 interges: "<<endl; for(i=0;i<10;i++){ cin>>a[i]; } Sort(&a[0],10); cout<<"Sorted order:"; for(i=0;i<10;i++){ cout<<a[i]<<" "; } cout<<endl; return 0; } void Sort(int *a, int n){ int i,j,k,tool; for(i=0;i<n;i++){ k=i; for(j=i;j<n;j++){ if(a[j]<a[k]) k=j; } tool=a[k]; a[k]=a[i]; a[i]=tool; } }
这种方法是最直接了当的方法,实参和形参的传递的数值和接受的数值都是指针