使用返回值动态传递内存(return)
堆内存可以作为返回值返回
#include <iostream>
using namespace std;
char *GetMemory3(int num)
{
char *p = (char *)malloc(sizeof(char)* num); // 申请堆内存
return p;
}
void Test3(void)
{
char *str = NULL;
str = GetMemory3(100);
strcpy(str, "hello");
cout << str << endl;
free(str);
}
栈区的“指针”不可返回
char *GetString(void)
{
char p[] = "hello world"; // p在栈区,hello world在文字常量区
return p; // 编译器将提出警告
}
void Test4(void)
{
char *str = NULL;
str = GetString(); // str 的内容是乱码
cout<< str << endl;
}
静态存储区可返回
char *GetString2(void)
{
char *p = "hello world"; // 存储于文字常量区,p为存储在栈区的地址
return p; //返回一个“只读”的内存块,文字常量区的内容不变,程序生命周期恒定不变
}
void Test5(void)
{
char *str = NULL;
str = GetString2();
cout<< str << endl;
}