1. 程式人生 > 其它 >C/C++返回區域性變數

C/C++返回區域性變數

原則:

能否正常返回這個值,要看這個值的內容或指向的內容是否被回收,導致空指標或者真實內容被擦除。【一旦返回值有指標或者地址,就需要著重考慮,而返回一個值是一般都可以的,可參考C++的臨時變數】

下面對不同情況說明。

1、返回指向常量的指標

#include <stdio.h> 
char *returnStr() 
{ 
    char *p="hello world!"; 
    return p; 
} 
int main() 
{ 
    char *str; 
    str=returnStr(); 
    printf("%s\n", str); 
    
return 0; }

這個沒有任何問題,因為"hello world!"是一個字串常量,存放在只讀資料段,把該字串常量存放的只讀資料段的首地址賦值給了指標,所以returnStr函式退出時,該該字串常量所在記憶體不會被回收,故能夠通過指標順利無誤的訪問。



2、不能返回陣列

#include <stdio.h> 
char *returnStr() 
{ 
    char p[]="hello world!"; 
    return p; 
} 
int main() 
{ 
    char *str; 
    str=returnStr(); 
    printf(
"%s\n", str); return 0; }

"hello world!"是區域性變數存放在棧中,而這裡的p是指向"hello world!"的首地址。當returnStr函式退出時,棧要清空,區域性變數的記憶體也被清空了,所以這時的函式返回的是一個已被釋放的記憶體地址,所以有可能打印出來的是亂碼。

3、返回普通值

int func()
{
    int a;
    ....
    return a; //允許
} 

int* func()
{
    int a;
    ....
    return &a; //無意義,不應該這樣做
} 

直接返回a,返回的是值,結果儲存在臨時變數中;返回&a時,是a的地址,而函式結束後,棧要清空,a的記憶體也被清空了,故結果肯定會異常。


4、可以把地址設定成static可正常返回

#include <stdio.h> 
char *returnStr() 
{ 
    static char p[]="hello world!"; 
    return p; 
} 
int main() 
{ 
    char *str; 
    str=returnStr(); 
    printf("%s\n", str); 
    
    return 0; 
} 

5、可以返回指向堆記憶體的指標

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);
}



長風破浪會有時,直掛雲帆濟滄海!
可通過下方連結找到博主
https://www.cnblogs.com/judes/p/10875138.html