轉自:https://blog.csdn.net/turkeyzhou/article/details/6104135#comments
四種返回字符串的方法:
1、 將字符串指針作為函數參數傳入,並返回該指針。
將地址由入參傳入:
char* fun(char*s)
{
if (s)
strcpy(s, "abc ");
return s;
}
2、 使用malloc函數動態分配內存,注意在主調函數中釋放。
char *fun()
{
char* s = (char*)calloc(100, sizeof(char*) );
if (s)
strcpy ( s , "abc " );
return s;
}
3、 返回一個靜態局部變量。
char* fun()
{
static char s[100];
strcpy(s, "abc ");
return s;
}
4、 使用全局變量。
char g_s[100];
char* fun()
{
strcpy(g_s, "abc ");
return s;
}
