C++ 从函数返回指针(函数外返回局部静态变量的地址)

来源:互联网 发布:org.apache.struts2 编辑:程序博客网 时间:2024/06/06 23:56
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;}


传递之后并不能得到正确的数组的值。

原因就是在数组内的数组没有设为静态。

更改:其他位置不变,只是将返回指针的函数中的数组变为静态即可:


运行结果: