The program generates a segmentation error when accessing the last element of a two-dimensional array in its processing cycle. Moreover, it has strange x and y values ​​at the beginning (but this is a minor issue). It is also strange that I thought of an option to go beyond the array, but an error occurs when accessing the last element. There is a suspicion of an error in the implementation of the mechanics of the for loop, but this is somehow too strange and it is even hard to believe ... What could be the error? Code (yes, I was looking for cout's error, do not hit) Amusing is the fact that the program does not exit at the right moment. Do not do the reinforced concrete checking of variables - iterators x and y for their values ​​... Why does a segfolt occur?

#include <cstdlib> #include <iomanip> #include <iostream> using namespace std; int main(int argc, char** argv) { const int X = 10; const int Y = 10; int field[X][Y]; int n = 0; //итератор для перечисления одномерных массивов int x, y, x_sec = 0; //x_iterator = X - 1; //y_iterator = Y - 1; int point_x[10], point_y[10]; //массивы в которые определяются координаты точек. for (x = 0; x < X; x++) { for (y = 0; y < Y; y++) { field[x][y] = rand() % 2; cout << setw(6) << left << field[x][y]; } cout << endl; } cout << x << " " << y << " " << endl; for (x = 0; x < X; //изначально было x<=X И y<=Y соответственно, что давало явный вылет. Ситуация от смены условий на строгие не поменялась. x++) // цикл обработки. тут возникает ошибка при условии что x = 10 { cout << "debug point 1" << endl; for (y = 0; y < Y; y++) //и y = 10 { cout << "x = " << x << " y = " << y << endl; cout << "debug point 2" << endl; if (field[x][y] > 0) //захват первой точки. Если она есть, то в point_x, point_y [n] пишутся координаты ненулевого элемента { cout << "адрес массива - " << x << " " << y << endl; cout << "debug point 3" << endl; point_x[n] = x; point_x[n] = y; n++; cout << "N = " << n << " point x = " << point_x[n] << " point y =" << point_y[n] << endl; cout << "debug point 4" << endl; for (x_sec = x; x_sec < X - 1; x_sec++) { cout << "адрес подмассива(s_sec) " << x_sec << " " << y << endl; cout << "debug point 5" << endl; if (field[x_sec][y] > 0) { cout << "debug point 6" << endl; point_x[n] = x_sec; point_y[n] = y; n++; cout << "x_sec = " << x_sec << " y = " << y << endl; cout << "debug point 7 | N = " << n << " point x = " << point_x[n] << " point y =" << point_y[n] << endl; } } } else { cout << "debug point 8" << endl; n = 0; point_x[n] = 0; point_y[n] = 0; cout << "debug point 9 " << x << " " << y << endl; } cout << "x = " << x << " y = " << y << endl; cin.get(); } } cout << point_x[0] << " " << point_y[0]; return 0; } 

    2 answers 2

    I will make my contribution. Look closely at this piece of code:

      point_x[n] = x; point_x[n] = y; n++; cout << "N = " << n << " point x = " << point_x[n] << " point y =" << point_y[n] << endl; 

    First, I suppose that you wanted to write point_y[n] = y in the second line, but the insidious copy-paste crept in. It turned out that you are rewriting the same memory section twice.

    Secondly, the expression n++ increments the value of the index n , which means that the next line already addresses the next element of the array. At the last iteration of the loop, this leads to going beyond the array. It would be correct to write this:

     int prev = n++; cout << "N = " << prev << " point x = " << point_x[prev] << " point y =" << point_y[prev] << endl; 

    Notice, there are several such problem areas in your code.

    • PS I did not understand the logic of the code. Indicated only obvious errors. - aleks.andr
    • The task: to overtake squares from a spray of points. The logic of operation is such that points (units) are searched for in a coordinate grid (two-dimensional array). If the first point is found in a line, then its coordinates are stored in the point_x and point_y [n-th] arrays. Further, in the same line, the second unit is searched for and its coordinates are memorized. From what was not written there, it was necessary to calculate the distance from the first to the second point and add this distance to y and check whether there are units or not. If there is, then it is square. - MarKo
    • Moreover, there is not an insidious copy-paste here, but a banal absent-mindedness, that piece I wrote with pens. Later, when I wrote a question here, I noticed and corrected it. - MarKo

    You have all arrays of size 10 , i.e. with indices from 0 to 9 . But in these cycles suddenly

     for (x = 0; x <= X; x++) for (y = 0; y <= Y; y++) 

    there is an access on indexes 10 because of weak comparison <= . This is an obvious departure beyond the array.

    At the same time, in the input cycle, everything was done correctly (comparisons in the cycle conditions are strict), but here suddenly for some reason x <= X and y <= Y Why?

    • tsimes that before it was as it should. - MarKo
    • hmm ... redid as it should. for some reason, earned O_o - MarKo
    • But no! Does not work! Even with the change of the iterator condition to x <X and y <Y (I use Geany, he didn’t want to rebuild the executable file at first) Now when x and y = 9 (as shown in the last cout in the processing cycle), a departure occurs - MarKo
    • @MarKo: Well, the error with the cycles is obvious. And then already look ... You have another great potential for departure outside the array - the point_x and point_y . What you have and is happening, for example. in "debug point 6" - "debug point 7". - AnT
    • and what's the matter? In the same place there are only 2 one-dimensional arrays which are connected by the number n which determines the number of the captured point. I agree with the fact that he is first cut off the excess, which is not good. And then I re-assign the value y to point_x which is bad! - MarKo