[問題] int *test() ?

看板C_and_CPP (C/C++)作者 (Alfred)時間16年前 (2010/03/17 12:41), 編輯推噓3(302)
留言5則, 4人參與, 最新討論串1/1
如題 我有看到一個片段程式如下 int *function(int b) { int *a; a = (int*)malloc(sizeof(int)*b); for(int i=0 ; i<b ; i++) a[i] = i; return a; } int main() { int *array, e; cin >> e; array = function(e); for(int i=0 ; i<e ; i++) cout << array[i] << endl; system("pause"); return 0; } 我大概知道它是要回傳array 這樣寫的原理是什麼呀? 這樣不會出問題嗎? 如果是class裡的member function可以這樣寫嗎? (像test::*func(){...}) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.64.183.226 ※ 編輯: skywillnosky 來自: 203.64.183.226 (03/17 12:44)

03/17 12:49, , 1F
他的問題是就...會忘了free...
03/17 12:49, 1F

03/17 12:49, , 2F
然後member function的話應該是 int* test::func()
03/17 12:49, 2F

03/17 13:43, , 3F
memory leak
03/17 13:43, 3F

03/17 13:52, , 4F
memory leak+1
03/17 13:52, 4F

03/17 18:33, , 5F
應該可以在return 0前 free array; 吧
03/17 18:33, 5F
文章代碼(AID): #1Be5sJZh (C_and_CPP)
文章代碼(AID): #1Be5sJZh (C_and_CPP)