为什么在这个动态数组中抛出异常
Why is an exception being thrown in this dynamic array?
我很难理解引发此异常的原因。我分配了一个数组来接收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.
}
}
- 从构造函数抛出异常时如何克服内存泄漏
- 函数如何通知用户它基于函数原型抛出异常?
- 对象初始化后在C++中显示 char 数组时的异常行为
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- VisualStudios 会抛出异常,而代码块不会 [C++]
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- ZMQ::send() 抛出异常并终止 QNX 进程.为什么以及如何从中恢复?
- new(std::nothrow) int[n] 抛出异常
- 为什么g_object_set抛出异常(vcruntime140.dll)?
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- C++子线程抛出异常
- 我们应该在抛出异常之前取消分配内存吗
- 有没有一种方法可以让OpenCLC++绑定为所有错误抛出异常
- 为什么访问模板化变体作为返回值抛出异常
- 为什么在这个动态数组中抛出异常
- ATL/COM:为什么 CComSafeArray::GetCount() 会为空数组抛出异常
- 将索引超出数组边界在 C++ 中的内核之前抛出异常或错误
- 创建2D数组时出现异常:在C++中重新抛出之前进行清理
- 有人能确切地解释一下,如果在堆上分配对象数组的过程中抛出异常,会发生什么吗
- 重载2D数组操作符并抛出异常