为什么在这个动态数组中抛出异常

Why is an exception being thrown in this dynamic array?

本文关键字:数组 抛出异常 动态 为什么      更新时间:2023-10-16

我很难理解引发此异常的原因。我分配了一个数组来接收100个int值,并希望将200以下的所有奇数存储到数组中(应该是100个整数值)。我正在努力理解为什么我的代码不起作用。

我已经调用了我的函数来分配一个由100个int值组成的数组。之后,我创建了一个for循环来迭代并将整数存储到数组中。然而,我创建的if语句只存储奇数。我不能理解的是,如果我把计数器设置为200并使用if语句,就会引发异常,但如果我不插入if语句,只把计数器设置成100,则存储1-100之间的所有数字,并且不会引发异常。

我唯一能想到的是,当我的计数器为200,并且我有if语句来捕获所有奇数时,不知何故,200以下的所有数字都存储在数组中,从而引发异常。

int *allocIntArray(int);
int main() {
int *a;
a = allocIntArray(100);
for (int count = 1; count < 200; count++) {
if (a[count] % 2 == 1) {
a[count] = count;
cout << a[count] << endl;
}
}
delete[] a;
return 0;
}
int *allocIntArray(int size) {
int *newarray = new int[size]();
return newarray;
}

当我查看程序输出时,它只显示奇数,但正在抛出异常。这告诉我的if声明是有效的,但有些事情被搞得一团糟。

我错过了什么?

感谢您的时间和知识。

错误原因

如果您有一个使用n元素创建的数组a,那么在尝试访问bouds中的数组元素时,这是未定义的行为。因此索引必须始终在0和n-1之间。

因此,一旦count为100,程序的行为就没有定义,因为在if-子句中评估条件已经试图访问越界。

随心所欲的调整

此外,程序逻辑中还有一个严重的错误:如果你想添加满足某种条件的数字,你需要两个计数器:一个用于迭代数字,另一个用于数组中使用的最后一个索引:

for (int nextitem=0, count = 1; count < 200; count++) {
if (count % 2 == 1) {   // not a[count], you need to test number itself
a[nextitem++] = count;
cout << count << endl;
if (nextitem == 100) {    // attention:  hard numbers should be avoided
cout << "Array full: " << nextitem << " items reached at " << count <<endl;
break;   // exit the for loop
}
}
} 

但是,这个解决方案要求您跟踪数组中的最后一个项和数组的大小(这里是硬编码的)。

矢量

你可能正在学习。但在C++中,更好的解决方案是使用vector而不是数组,并使用push_back()。矢量管理内存,这样您就可以专注于您的算法。完整的程序看起来像:

vector<int> a;
for (int count = 1; count < 200; count++) {
if (count % 2 == 1) {
a.push_back(count);
cout << count << endl;
}
}
cout << "Added " << a.size() << " elements" <<endl; 
cout << "10th element: "<< a[9] << endl; 

问题不在于存储了多少数字,而在于存储在哪里;您将101存储在a[101]中,这显然是错误的。

如果第i个奇数是C,则正确的索引是i-1,而不是C。

最可读的更改可能是引入一个新的计数器变量。

int main() {
int a[100] = {0}; 
int count = 0;
for (int number = 1; number < 200; number++) {
if (number % 2 == 1) {
a[count] = number;
count += 1; 
}
}
}

我认为将这一问题从搜索问题转变为生成问题会更容易纠正。

如果你碰巧记得,对于一些A,每个奇数C都可以写在形式2 * A + 1上,你会发现你要寻找的序列是

2*0+1, 2*1+1, 2*2+1, ..., 2*99+1

所以

int main()
{
int numbers[100] = {0};
for (int i = 0; i < 100; i++)
{
numbers[i] = 2 * i + 1;
}
}

你也可以反过来,循环奇数并将其存储在正确的位置:

int main()
{
int numbers[100] = {0};
for (int i = 1; i < 200; i += 2) // This loops over the odd numbers.
{
numbers[i/2] = i;  // Integer division makes this work.
}
}