Segmetantion fault

Write your question here.
So im writing a program where where i have to find how many rectangles exist in my array where if i have the number 1 then this is part of my rectangle or if have 0 there is nothing .It's like a boarding game ,but when i build and run my program with code blocks it crashes and when i used debug this message appears "Program received signal SIGSEGV, Segmentation fault." Can please someone explain what is happening here?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>

using namespace std;

int main()
{
    int array[1000][1000];
    int N,M;
    int ships = 0;
    cin >> N >> M;
    for ( int  i = 0; i < N; i++){
        for  ( int  j = 0; j < M; j++){
            cin >> array[i][j];
        }
    }
     for ( int  i = 0; i < N; i++){
        for ( int  j = 0; j < M; j++){
            if ( array[i][j] == 1 && array[i][j-1] == 0 && array[i-1][j] == 0 && array[i-1][j-1] == 0){
                ships++;
            }
        }
     }
    cout << ships << endl;
    return 0;
Do you enter any values or does it crash before then?

Putting 1 million int values on the stack memory could be a problem; that would be 4 million bytes (or maybe 8 million depending on your system), which is more than the stack memory allocated by default on some systems.

Make the 2D int array smaller.

And then don't use one at all and use vectors instead. Arrays are for intermediate programmers; as a beginner, you should use vectors.
You are accessing an array out of bounds on line 18.
What do you think array[i][j-1] will be looking at if j = 0, for example?

Given what you are doing at present you could start i and j both from 1 on lines 16 and 17.

On the other hand, I'm not convinced this is how you identify ships ...
Alright thank you very much i should just change my array from array[1000][1000] to array[100000][100000]
Alright thank you very much i should just change my array from array[1000][1000] to array[100000][100000]


That will make one problem worse. Did you read what @Repeater wrote? "smaller"
Last edited on
Topic archived. No new replies allowed.