C函数返回指针
常规程序中,函数返回的指针通常应该是以下几种形式:
(1)指向静态(static)变量;
(2)指向专门申请分配的(如用malloc)空间;
(3)指向常量区(如指向字符串"hello");
(4)指向全局变量;
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#define ConstBuf "Hello GetConstBuf"
char* GlobalBuf;
char* GetMallocBuf();
char* GetStaticBuf();
char* GetConstBuf();
char* GetGlobalBuf();
int main(int argc, char* argv[])
{
char* pMalloc = GetMallocBuf();
char* pStatic = GetStaticBuf();
char* pConst = GetConstBuf();
char* pGlobal = GetGlobalBuf();
printf("main:%s.\n",pMalloc);
printf("main:%s.\n",pStatic);
printf("main:%s.\n",pConst);
printf("main:%s.\n",pGlobal);
free(pMalloc);
//free(pStatic); 不允许free 程序运行完后自动释放
//free(pConst); 不允许free 常量,程序执行完毕后自动释放
free(pGlobal);
getchar();
return 0;
}
//通过malloc堆内存返回指针
char* GetMallocBuf()
{
char* buf = (char*)malloc(30);
if(buf==NULL)
{
perror("func GetMallocBuf malloc error.\n");
exit(1);
}
strcpy(buf,"Hello GetMallocBuf");
return buf;
}
//通过静态变量返回指针
char* GetStaticBuf()
{
static char buf[] = "Hello GetStaticBuf";
return buf;
}
//通过指向常量返回指针
char* GetConstBuf()
{
char* buf;
buf = ConstBuf;
return buf;
}
//通过全局变量返回指针
char* GetGlobalBuf()
{
GlobalBuf = (char*)malloc(30);
if(GlobalBuf==NULL)
{
perror("func GetGlobalBuf malloc error.\n");
exit(1);
}
strcpy(GlobalBuf,"Hello GetGlobalBuf");
return GlobalBuf;
}