放假的时候再继续重新自学c++。今天看到函数和数组
c++中,在函数中数组参数对应的都是指针。重点在于:其一讲数组地址作为参数可以节省复制整个数组的时间和内存(只要传递一个数组头的地址),如果数组很大,使用拷贝的系统开销(空间以及时间)非常大。其二:使用原始数据增加了破坏数组的风险(书上看的,不是很理解)。
接下来想说下自己对数组函数的理解:
#include <iostream>
using namespace std;
const int ArrLength=8;
int *number(int *arr,int n);
int main()
{
int N,int_Number;
int *Number;
int arr[ArrLength]={1,2,4,8,16,32,64,128};
cout<<"put into a int which is bigger than -1 and small than 8"<<endl;
cin>>N;
while(N<-1||N>7)
{
cout<<"put into a int which is bigger than -1 and small than 8"<<endl;
cin>>N;
}
Number=number(arr,N);
cout<<"the number is:";
cout<<*Number;//cout<<*number(arr,N);
int_Numbe=*number(arr,N);
cout<<"the number is:";
cout<<int _Number;
cin.get();
cin.get();
return 0;
}
int *number(int *arr,int n)
{
int num;
num =*(arr+n);
return #
}
输入2;输出:4343xxxx(一个比较大的数字),4(需要的数值);
结论,在一数组函数中,可以返回值或是地址。返回的是值的话没什么好讲。如果返回的地址的话:一个使用指针来接受,一个是使用int类型来接受指针所指向的值。(分别对应例子中的红色和蓝色)。
再针对红色代码来看,为什么输出的是一个比较大的数字,而红色部分注释部分依然可以输出4这个需要的答案。
Number是一个int指针,Number=number(arr,N);个人认为Number的确指向函数正确运算之后的4所指向的那块地址。 可是函数结束之后,系统将函数中的4的值delete掉了,所以在之后输出阶段 cout<<*Number;Number依然指向那块地址,而对应地址所在的值已经被系统重新非配了。这就是为什么cout<<*number(arr,N);可以正确输出的原因
还有对于目前简单的数组指针来说,这里有2个恒等式:(arr数组,ar是对应的数组指针)
arr[i]==*(ar+i); //值
&arr[i]==ar+i; //地址