【发布时间】:2018-11-26 17:10:25
【问题描述】:
嘿,我知道这很简单,但由于某种原因,我的日子比我想象的要艰难。我想要做的只是如果我的动态数组的大小等于其中的实际元素数量(意味着它已满),那么我想将数组的大小加倍并添加元素
int add_element(int *array, int size , int &count)
{
int temp;
cout << "What number do you want to add ? " << endl;
cin >> temp;
if(count = size)
{
copy(array, size);
count++;
array[count] = temp;
}
return count;
}
void copy(int *oldArr , int size)
{
int temp = size * 2;
int *newArr = new int[temp];
for (int i = 0; i < size; i++)
{
newArr[i] = oldArr[i];
}
//delete[] oldArr;
oldArr = NULL;
oldArr = newArr;
delete[] oldArr;
我遇到的问题是,实际上并没有将数组的大小加倍,因为当我尝试查找元素时,它只是返回地址空间。 任何帮助将不胜感激
***********编辑********* 我继续进行了这些更改,但我的数组似乎仍然没有改变大小
void add_element(int* &array, int size , int &count)
{
int temp;
cout << "What number do you want to add ? " << endl;
cin >> temp;
if(count == size)
{
copy(array, size);
count++;
array[count] = temp;
}
}
void copy(int* &oldArr , int size)
{
int temp = size * 2;
int *newArr = new int[temp];
for (int i = 0; i < size; i++)
{
newArr[i] = oldArr[i];
}
delete[] oldArr;
oldArr = newArr;
【问题讨论】:
-
count = size应改为==。 -
@buc 很好,但它仍然没有增加数组的大小
-
我刚注意到,又发现3个错误,看我的回答。
-
您是否在
add_element之前声明了copy?如果不是,并且您之前还声明了using namespace std(基于 cout 和 cin,看起来您已经声明了),那么您实际上可能在add_element中使用了 en.cppreference.com/w/cpp/algorithm/copy。
标签: c++ arrays c++11 dynamic-arrays