[問題] 如何手動管理 C array 的記憶體

看板C_and_CPP (C/C++)作者 (XareeLee)時間12年前 (2013/12/01 15:01), 編輯推噓1(107)
留言8則, 6人參與, 最新討論串1/1
想請教一下前輩關於 C array 的問題 假如 C array 的 size 是動態決定的,那麼是否需要手動管理記憶體? 我想要傳入一個指標到一個函式中 該指標會在函式中 改指向一個 C array 來讓外部使用 不知道下面的寫法有沒有問題?有沒有需要記憶體管理的部份? /** * 傳入 list 和 count 的指標,會得到 C array 以及數量 */ void getList(int *list, int *count){ // 取得總共 elements 的數量 int totalListCount = getTotalListCount(); // 初始化一個 array int theList[totalListCount]; memset( theList, 0, sizeof(int)*totalListCount ); // 設定 elements for (int i = 0; i < totalListCount; i++) { theList[i] = theElementAtIndex(i); } // 將指標指向此段記憶體位置 *count = totalListCount; *list = theList; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 42.66.184.147

12/01 15:11, , 1F
有問題,需要記憶體管理,需要回傳指標或傳入指標的指標
12/01 15:11, 1F

12/01 15:17, , 2F
不好意思 請問要怎麼修改呢? ^^|
12/01 15:17, 2F

12/01 15:23, , 3F
改用 C++
12/01 15:23, 3F

12/01 15:43, , 4F
用int* getList(){ int*p; p=malloc(n); return p;}
12/01 15:43, 4F

12/01 15:44, , 5F
沒用時記得free
12/01 15:44, 5F

12/01 21:29, , 6F
13戒之5
12/01 21:29, 6F

12/01 21:39, , 7F
13戒之13
12/01 21:39, 7F

12/02 00:26, , 8F
int **list才對吧@_@
12/02 00:26, 8F
文章代碼(AID): #1Icjwlvp (C_and_CPP)
文章代碼(AID): #1Icjwlvp (C_and_CPP)