【发布时间】:2018-03-01 05:13:39
【问题描述】:
我正在制作一个程序,从用户提供的数组的索引中删除一个数字,显示新数组,然后要求用户在他们选择的任何索引处插入一个数字。该程序的第一部分在删除索引时运行良好,但我在添加索引和数字时遇到了麻烦。例如,如果用户从索引 5 中删除数字后的 NEW 数组是:12 34 45 2 8 16 180 182 22,如果您记得数组从 0 开始,这是正确的,那么他们请求例如添加索引 5再次使用数字 78,它变得一团糟。它显示 12 34 45 2 78 8 16 180 182 22 (然后由于某种原因它还输出数字 -858993460?)所以问题基本上是它在它应该之前添加了新索引和第一索引。如果这听起来很令人困惑,我很抱歉,但我已经坚持了几个小时。谢谢!
//This program demos basic arrays
#include <iostream>
using namespace std;
const int CAP = 10;
int main()
{
int size;
int list[CAP] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
size = 10;
int i, delIndex, addIndex, newInt = 0;
cout << "Your list is: " << endl;
for (i = 0; i < CAP; i++)
{
cout << list[i] << endl;
}
//Deleting an index
cout << "\nPlease enter index to delete from: ";
cin >> delIndex;
for (i = delIndex; i <= 10; i++)
{
list[i] = list[i + 1];
}
cout << "The index position you specified has been deleted." << endl;
cout << "The new array is: " << endl;
for (i = 0; i < (size - 1); i++)
{
cout << list[i] << endl;
}
//Adding an index
cout << "\nNow, please enter the index position to add to: " << endl;
cin >> addIndex;
cout << "\nEnter the number to add to the index: " << endl;
cin >> newInt;
for (i = size - 1; i >= addIndex - 1; i--)
{
list[i + 1] = list[i];
}
list[addIndex - 1] = newInt;
size++;
cout << "The number has been added at the specified index position." <<
endl;
cout << "The new array is: " << endl;
for (i = 0; i < size; i++)
{
cout << list[i] << endl;
}
return 0;
}
【问题讨论】:
-
for (i = delIndex; i <= 10; i++) {list[i] = list[i + 1];}-- 此循环写入超出数组范围的项目。其次,数组无法调整大小,因此“删除元素”或“添加元素”不是您想要做的。 -
那我不知道怎么说了。如果您测试我的程序,用户可以请求索引删除一个数字。这些是我的指示,不是我编造的。
-
它不是“工作正常”。你很幸运它有效。该数组有 10 个项目,但您访问的项目远远超出
list[9]。您正在访问索引 10 和 11,因此会造成缓冲区溢出并发生 未定义的行为。 -
将
for (i = delIndex; i <= 10; i++)更改为for (i = delIndex; i < 9; i++) -
@Ishpreet --
for (i = delIndex; i < 10; i++)-- 在最后一次迭代中仍然超出范围。