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