1
我正在做一個家庭作業,我試圖找出一個好方法。動態數組分配和複製到較大
我想複製一個類型說「狗」的動態數組,其中包含兩個結構的值到另一個「臨時」動態數組的大小的兩倍。一旦完成,我想原來的數組名,以取代「臨時」
pseudo:
user inserts some newnum of elements ->call to func
check if sizeof(array) < (n_items + newnum)
yes: need to grow array
//here's the trouble part
create temp.array 2x sizeof(dog.array), copy dog.array to bigger temp.array
//would i be better off free(dog.array) and then create a new instance of
//dog.array that is now the same size of the temp.array and copy again/free(temp)
//or is there another method to do "new" dog.array = temp.array
當我的程序檢查室中插入多個值進入此陣,它會繼續和分配兩倍大小的新數組如果第一個已滿。在這之後,它將for循環中的數據交換出來,這很好。我很好奇如何去釋放舊的分配空間,然後重新命名新的「臨時」數組以匹配舊的數組......或者可能只是刪除與舊數組相關的數據,並且只需將同名的指針「臨時」之一。不知道如何去做這件事。
爲什麼要在這裏使用malloc而不是realloc? – 2012-01-30 23:20:04
謝謝我忘了提及我被指示不要使用realloc – 2012-01-30 23:40:15
@DavidHeffernan:如果你有家庭作業要做什麼? – 2012-01-30 23:46:33