2014-09-28 141 views
0
void insert(int*arr, int element,int index) 
{ 
    if (index < SIZE) 
    { 
     arr[index] = element; 
    } 
    else 
    { 
     int* new_array = new int[SIZE + 1]; 
     int i = 0; 
     for (i = 0; i < SIZE; i++) 
     { 
      new_array[i] = arr[i]; 
     } 
     new_array[i] = element; 
     SIZE++; 
     printArray(new_array); 
    } 



} 

我已經在C++中插入了一個插入函數,它將在數組的特定索引處插入值。索引增加後,我創建了一個新數組並將數組從小數組複製到其中。 問題是,只是循環打印數組的printArray函數在插入函數內調用時效果不錯,否則當我從數組的主最後一個值調用printArray時,它是垃圾原因?在數組中插入元素

+1

當您創建新陣列並複製舊陣列時,舊陣列仍然具有相同的值。 – 2014-09-28 21:09:10

+1

你可以使用'std :: vector'已經有功能插入中間。 – 2014-09-28 21:18:05

回答

4

您需要刪除舊的陣列,並在它的位置返回新的數組,如:

void insert(int* &arr, int element, int index) // <<< make `arr` a reference so that we can modify it 
{ 
    if (index < SIZE) 
    { 
     arr[index] = element; 
    } 
    else 
    { 
     int* new_array = new int[SIZE + 1]; 
     for (int i = 0; i < SIZE; i++) 
     { 
      new_array[i] = arr[i]; 
     } 
     new_array[SIZE] = element; 
     SIZE++;   // <<< NB: using a global for this is not a great idea! 
     delete [] arr; // <<< delete old `arr` 
     arr = new_array; // <<< replace it with `new_array` 
    } 
} 

LIVE DEMO

請注意,您的陣列的這一切明確的管理水平低下消失,如果你開始使用適當的C++習慣用法,例如std::vector<int>而不是C型int *陣列。

+0

它沒有工作,所有打印的值變成垃圾。 – 2014-09-28 21:17:25

+0

您是否完全按照過帳進行了所有3項更改? – 2014-09-28 21:18:30

+0

第一次更改在VS2013中給出了錯誤「未解決的外部事件」。 – 2014-09-28 21:19:26