首页 > 解决方案 > 在数组索引上抛出异常

问题描述

我需要找到一个总和最大的列。当我尝试访问数组元素时显示下一个错误

在 ConsoleApplication1.exe 中的 0x00565263 处引发异常:0xC0000005:访问冲突读取位置 0x00511048。

#include <iostream>
using namespace std;

int main() {
    int numbers[101][101];
    int n, m, sum = 0, sum_max = 0, idx = 0, counter = 1;
    cin >> n >> m;      //enter size of your array

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                cin >> numbers[i][j];
            }
        }

        for (int i = 1; true; i++) {
            if (i == n + 1) {
                n = 1;
                counter++;
            }
            sum += numbers[i][counter];

            if (sum_max < sum) {
                sum_max = sum;
                idx = counter;
            }
        }
        cout << idx;
}

标签: c++

解决方案


First, you should not allocate a fixed-size array, and then let the user enter a variable amount of data. While this may "work" when respecting the maximum size, it is bound to eventually fail-by-design.
Also, it is bad for memory layout to have a partially filled array which is really an array of a smaller size with gaps in between. Your processor caches will hate you.

You should new the array of correct size (or use a vector which you reserve to n*m, if you will, you can still index into the buffer in two dimensions then, although that's less elegant than I like it) instead.
If it is agreeable that your program maybe runs 2% slower overall (maybe, not even necessarily!), you might create a vector of vectors. That has the immense advantage that you do not really need to know the size any more for finding the max. You can use range-based for or even a std:: algorithm. Which eliminates the chance of making an out-of-index error altogether. And it looks much nicer.

Next, you seem to start indices at 1 for some reason (Fortran programmer?!). C++ indices start at zero.

Then, that second loop of yours has no exit condition. It will run forever, and so counter will eventually, no matter what size the array has, reach a value where you access an address that isn't good. At that point, you get a segmentation fault (0xC0000005). This is what you see.
Also, you seem to be doing something like (incorrect) modulo operation with a conditional branch. There exists an operator for that, which has the advantage that it also works correctly, i.e. starting the index at zero: % n.


推荐阅读