C++中关于函数内静态数组和new分配的动态数组的区别分析

#include<iostream>
using namespace std;
char *GetFilePath();
void main()
{
   cout<<GetFilePath()<<endl;
}
char *GetFilePath()
{
cout<<"请输入要传送的文件全路径,如:E:/图片/Saved Pictures/7.jpg"<<endl;
char filePath[256];
   // cin>>filePath;
strcpy(filePath,"E:/图片/Saved Pictures/7.jpg");
return filePath;
}
//----------------------------------------------------------------
#include<iostream>
using namespace std;
char *GetFilePath();
void main()
{
   cout<<GetFilePath()<<endl;
}
char *GetFilePath()
{
cout<<"请输入要传送的文件全路径,如:E:/图片/Saved Pictures/7.jpg"<<endl;
char filePath[256];
strcpy(filePath,"E:/图片/Saved Pictures/7.jpg");
char *p=new char[strlen(filePath)+1];
strcpy(p,filePath);
return p;
}
/*上述第一段代码输出结果会出现乱码,而第二段代码不会出现乱码,原因:
因为[]静态数组是在栈中申请的,而函数中的局部变量也是在栈中的,
而new动态数组是在堆中的分配的,所以函数返回后,栈中的东西被自动释放,
而堆中的东西如果没有delete不会自动释放。*/

原文地址:https://www.cnblogs.com/zztong/p/6695196.html