我有以下代碼:
int* foo(){
int x = 15;
return &x; }
我理解為什么不這樣做,因為在函式完成后區域變數地址從堆疊中被擦除并且它變成了一個懸空指標。問題是,如何在不使 xa 靜態變數的情況下使其成為懸空變數
uj5u.com熱心網友回復:
有福的方法是:
回傳一個值而不是地址
int foo(){ int x = 15; return x; }讓來電者提供地址
int *foo(int *x) { *x = 15; return x; }或者
void foo(int *x) { *x = 15; }回傳動態(已分配)記憶體:
int *foo() { int *x = malloc(sizeof(*x)); // should test valid allocation but omitted for brievety *x = 15; return x; }請注意,呼叫者將獲得所有權或分配的記憶體,并負責稍后釋放它。
uj5u.com熱心網友回復:
從函式內部的堆分配記憶體
int *f() {
int *foo = malloc(sizeof(int));
if(!foo) {
// Do appropriate error handling here
}
return foo;
}
但不要忘記free在某些時候。
或者你傳入一個指向位于函式外部的變數的指標:
void f(int *foo) {
*foo = 42;
}
void g() {
int goo;
f(&goo);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/356260.html
上一篇:void函式不回傳任何內容-C
