繁体   English   中英

为什么在此动态数组中引发异常?

[英]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 ,则尝试从Bod中访问数组元素时,这是未定义的行为。 因此索引必须始终在0到n-1之间。

因此,一旦count为100,您的程序的行为就不会被定义,因为评估if -clause中的条件已尝试超出范围。

调整即可满足您的需求

此外,程序逻辑中存在一个严重的错误:如果要添加满足某种条件的数字,则需要2个计数器:一个用于对数字进行迭代,另一个用于数组中使用的最后一个索引:

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; 
       }
    }
}

我认为将其从搜索问题转换为世代问题会更容易解决问题。

如果您记得每个奇数C都可以2 * A + 1的形式写给A ,那么您会发现要查找的序列是

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.
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM