C++ 不支持在函数外返回局部变量的地址,除非定义局部变量为
static
变量。
错误代码:
int main(){
int *p;
p=funcGetPointer();
for (int i = 0; i < 10; i++)
{
cout<<"*(p+"<<i<<"): ";
cout<<*(p+i)<<endl;
}
return 0;
}
//函数返回指针
int * funcGetPointer(){
int arr[10];
srand((unsigned)time(NULL));
for (int i = 0; i < 10; i++)
{
arr[i]=rand()%7+2;
}
cout<<"The contents is:"<<endl;
for (int i = 0; i < 10; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
return arr;
}
传递之后并不能得到正确的数组的值。
原因就是在数组内的数组没有设为静态。
更改:其他位置不变,只是将返回指针的函数中的数组变为静态即可:
运行结果: