c++ - 在数组索引上抛出异常
问题描述
我需要找到一个总和最大的列。当我尝试访问数组元素时显示下一个错误
在 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;
}
解决方案
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 vector
s. 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
.
推荐阅读
- python - 神经网络攻击傻瓜(FGSM)
- microsoft-graph-api - 通过 msgraph 搜索 Sharepoint 列表和文档
- java - 如何根据选择的主题显示不同的启动画面?
- php - 在 Laravel 中生成上传视频的缩略图
- vb.net - 动态文本框颜色变化
- java - Kd 树级顺序遍历
- fortran - 使用 OpenMP 并行的矩阵乘法不会提高执行时间
- java - 可以在 ANT 任务的类路径中引用 Spring Boot jar 中的类吗?
- java - 批量插入时如何选择正确的批量大小
- python - Python - 从源根目录导入会导致“没有名为”的模块