1. 程式人生 > >C語言返回字串的四種方式

C語言返回字串的四種方式

C語言返回字串有四種方式:1。使用堆空間,返回申請的堆地址,注意釋放2。函式引數傳遞指標,返回該指標3。返回函式內定義的靜態變數(共享)4。返回全域性變數使用分配的記憶體,地址是有效 
一:使用堆空間,返回申請的堆地址
char *fun() 
{ 
       char* s = (char*)calloc(100, sizeof(char*) ); 
       if (s) 
       strcpy ( s , "abc " ); 
       return s; 
} 
但這種方式需要注意,必須由使用將將返回的地址free掉 
二:將地址由入參傳入 
char* fun(char*s) 
{ 
     if (s) 
     strcpy(s, "abc "); 
     return s; 
} 
這種方式呼叫都要注意給s分配的大小是足夠。 
可以這樣: 
char* fun(char*s, int len) 
{ 
     if (s) 
    { 
       strncpy(s, "abc ", len-1); 
       s[len-1] = 0; 
    } 
    return s; 
} 
三:使用區域性靜態變數 
char* fun() 
{ 
static char s[100]; 
strcpy(s, "abc "); 
return s; 
} 
這種方式需要注意,不要修改返回的這個字串,由於是共享地址,對它的修改會反應到每個呼叫者的。可以在前面加一個const: 
const char* fun() 
{ 
static char s[100]; 
strcpy(s, "abc "); 
return s; 
} 
四:使用全域性變數 (或靜態全域性變數)
char g_s[100]; 
char* fun() 
{ 
strcpy(g_s, "abc "); 
return s; 
} 
或:
#define BUFSIZE 4096
static char *_result_str = (char *)malloc(BUFSIZE);     // FIXME: 希望足夠了; 
char* fun() 
{ 
char *str = _result_str;
strcpy(str, "abc "); 
return str; 
} 
同樣的,也要注意這個變數可儲存的最大空間。