gpt4 book ai didi

c++ - 内存位置作为放大动态数组中的最后一个值

转载 作者:行者123 更新时间:2023-11-27 22:46:06 24 4
gpt4 key购买 nike

<分区>

我将一个动态数组传递给一个函数,该函数具有一个要添加到数组的值,当我动态地放大和重置数组并遍历数组时,我发现数组的最后一个值是垃圾值而不是预期的。我已经查看了其他一些关于 SO 的帖子以及一些文档,但我对自己做错了什么感到困惑。 我更愿意使用 vector ,但不幸的是我的作业需要一个动态数组。有什么想法吗?谢谢。

上面的帖子是通过引用传递指向 vector 的指针,与扩大动态数组无关

主要

cout << "Please enter the size of the array of integers you would like to create: ";
cin >> size;

cout << "\nPlease enter your integers:\n";

int *integerArray = new int[size];

//store values in array
for (int dynamicArrayDataCounter = 0; dynamicArrayDataCounter < size; dynamicArrayDataCounter++)
cin >> integerArray[dynamicArrayDataCounter];

cout << "\n Please enter the integer you would like to insert into this array: ";
cin >> userInt;

InsertIntegerToSortedList(integerArray, userInt, size);

//Print array for proof
for (int counterPrinter = 0; counterPrinter < size + 1; counterPrinter++)
cout << endl << integerArray[counterPrinter];

//Remove memory and repoint dangling pointer
delete [] integerArray;
integerArray = NULL;

return 0;
}

函数

void InsertIntegerToSortedList(int *integerArray, int userInteger, int size)
{
//Declare new array to add index position for integerArray
int *resizedArray = new int[size + 1];
bool numInserted = false;

for (int counter = 0; counter < size + 1; counter++)
{
if (integerArray[counter] < userInteger)
{
resizedArray[counter] = integerArray[counter];
}
else if ((integerArray[counter] > userInteger && integerArray[counter - 1] < userInteger) || integerArray[counter] == userInteger || (integerArray[counter] <= userInteger && size - counter == 1))
{
resizedArray[counter] = userInteger;

numInserted = true;
}
else if (numInserted)
resizedArray[counter] = integerArray[counter - 1];
}

//Store resizedArray values in integerArray
integerArray = resizedArray;

//Remove dynamic array on heap and repoint dangling pointer
delete[] resizedArray;
resizedArray = NULL;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com