2014-09-28 144 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