局部变量会在对应函数运行完自动释放,可以返回值,但是切记不要返回局部变量的地址。
new可以在堆区开辟内存,返回的是地址。如new int(1)
#include <iostream>
using namespace std;
int* arr(){
int* p=new int(1);
return p;
}
int main(){
int* p=arr();
cout<<*p<<endl ;
cout<<*p<<endl ;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int *arr(){
int a=3;
return &a;
}
int main(){
int *p=arr();
cout<<*p<<endl ;
cout<<*p<<endl;
system("pause");
return 0;
}
1,对比这两个函数,可以看出如果已经定义了指针类型,那么可以直接返回,如果未定义指针类型,那么当接收返回的类型为指针类型时,返回的类型应该是引用取地址
2,如果用new开辟了堆区地址,那么可以用delete释放堆区地址。
1344

被折叠的 条评论
为什么被折叠?



