调整数组大小并添加元素 C++

resize array and add element c++

本文关键字:添加 元素 C++ 数组 调整      更新时间:2023-10-16

嘿,我知道这很简单,但由于某种原因,我比我想象的更艰难。我试图做的是,如果我的动态数组的大小等于其中元素的实际数量(意味着它是满的(,那么我想将数组的大小加倍并添加元素

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;

代码中有几个错误。

首先,在add_element中,您想测试项目计数是否等于数组大小,但您不小心覆盖了count变量:

if(count = size)   // this assigns count

应替换为

if(count == size)

其次,删除新分配的阵列而不是旧阵列:

oldArr = newArr;
delete[] oldArr;    // this will effectively deallocate newArr

您应该更改这些行的顺序:

delete[] oldArr;    // it deletes oldArr
oldArr = newArr;    // and then points it to newArr

第三,按值将指针传递给数组。这样,当分配新数组时,您将无法将新数组的地址返回给函数的调用方。您应该通过引用传递数组指针,类似于count

int add_element(int* &array, int size, int &count)

void copy(int* &oldArr, int size)

第四,从函数add_element返回两次count:既作为返回值,又作为 In-Out 参数。虽然,这在技术上不是问题,但绝对没有必要。我建议更改add_element以返回void.

更新

最后,但至少不是,我忽略了第五个问题。与需要从函数返回新数组指针的方式类似,数组大小也必须这样做。因此size应该通过引用传递,并且应该正确更新:

int add_element(int* &array, int &size, int &count)

void copy(int* &oldArr, int &size) {   // pass size by reference
int temp = size * 2;
// ...
oldArr = newArr;
size = temp;   // update size
}