I need to find a column with a greatest sum. while I am try to access arrays element shows next mistake
exception thrown at 0x00565263 in ConsoleApplication1.exe: 0xC0000005: Access violation reading location 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
.
Use the std::array
which is a fixed size array.
Instead of
int numbers[101][101];
use a std::array
std::array< std::array<int, 101>, 101 > numbers;
Now you will get better diagnostics when debugging - also you can use at
function that will throw an exception instead of giving undefined behavior when accessing out of bounds elements.
example:
cin >> numbers.at(i).at(j);
Alternatively you might want to use a std::vector
if you need a dynamic array.
User contributions licensed under CC BY-SA 3.0