原則:盡量不要返回一個局部變量的指針或引用,因為函數執行完之后,將釋放分配給局部變量的存儲空間,局部變量只是臨時的存儲空間,此時,對局部變量的引用和地址就會返回不確定的內存,但可以返回局部變量本身,局部變量實際上是返回變量值的拷貝,雖然在函數調用結束后所在內存會被釋放回收掉,但返回值不是地址,而是局部變量的拷貝副本。
1.返回局部變量(沒有問題)
#include <stdio.h> #include <string.h> int add(int x, int y) { int sum = x + y; return sum; } int main() { int a = 3, b = 5; printf("%d+%d=%d",a,b,add(a,b)); }
2.返回局部變量指針(出現錯誤)
#include <stdio.h> #include <string.h> int* add(int x, int y) { int sum = x + y; return ∑ } int main() { int a = 3, b = 5; printf("%d+%d=%d",a,b,*add(a,b)); }
總結
局部變量:
局部變量分為局部自動變量和局部靜態變量,無論自動還是靜態,返回局部變量都是沒有問題的,因為返回值不是地址,雖然在函數調用結束后(棧區)局部變量的內存會被釋放回收掉,但函數返回的是變量拷貝副本。
局部指針:
局部指針分為局部靜態指針和局部自動指針,可以返回一個局部靜態指針的地址,但不應該返回一個局部自動指針的地址,除非自動指針的地址指向數據區或堆區。
返回局部靜態指針變量的情況:
#include <stdio.h> #include <string.h> char * test(){ static char arr[] = "hello world!"; return arr; } int main() { printf("%s",test()); }
返回局部自動指針,但指向數據區的情況:
#include <stdio.h> #include <string.h> char * test(){ char *arr = "hello world"; //字符常量 return arr; } int main() { printf("%s",test()); }
該如何解決:
- 使用靜態變量
- 使用全局變量