2012-03-14 86 views
0

我有一個作業問題來完成此方法。我真的不知道該怎麼做。鑑於此psuedocode可以有人幫我寫這種方法?函數將用戶輸入並將其添加到數組

/* 
    make a new array of the old size plus the new size 
    copy from the old to the new 
    add the new characters 
    don't forget to clean up the old array (free it) 
    before you leave this function 
*/ 

char * add(char * array, int num) 
{ 
    return array; 

} 
+3

目前尚不清楚新尺寸是什麼?也許這需要作爲函數的參數來傳遞?什麼是新的字符被添加到新的陣列? – 2012-03-14 17:21:24

+0

你的函數簽名是否必須是char * add(char * array,int num)'? – 2012-03-14 18:19:39

+0

是的,它必須具有該簽名 – anthony 2012-03-14 19:42:28

回答

1

由於這是C,看看realloc - 但你還需要有舊的尺寸參數(或者使用strlen

1

下面是一個僞代碼:

char * add(char * old_array, int old_size, char *additions, int new_size) 
{ 
    malloc new_size bytes and assign to new_array 
    memcpy old_size bytes from old_array into the new_array 
    add additions into new_array starting from (new_array+old_size) 
    free the old_araray 
    return new_array; 

} 
+1

realloc有點簡單。 – 2012-03-14 17:37:27

+0

@EdHeal,從OP「不要忘記清理舊數組(免費)」 – perreal 2012-03-14 17:38:09

+0

realloc爲您複製和釋放(如果需要)分類。 – 2012-03-14 17:49:16

相關問題