Xcode on Mac Compiles, but gives an error ( Threat 1: signal SIGABRT ) if the matrix is ​​not square.

 #include <iostream> using namespace std; const int N=3; const int M=10; int main(int argc, const char * argv[]) { int a[N][M]; for(int i=0;i<M;i++){ for(int j=0;j<N;j++){ a[i][j]=rand()%2; cout<<a[i][j]<<" "; } cout<<endl; } return 0; } 
  • 2
    Swap M and N in cycles. - post_zeew

2 answers 2

Swap M and N in cycles.

You declare your array as int a[N][M]; where N = 3 and M = 10 .

You access an array using two indices a[i][j] .

Index i must be between 0 and N , and j must be between 0 and M

In your version, you go beyond the array.

  • Blunted, thank you) - BigBoy Jack
  • @BigBoyJack, If the answer is correct, click on the check mark to the left of it. - post_zeew

As already noted in the comments, you have incorrectly set upper limits for the cycles.

 int a[N][M]; for(int i=0;i<M;i++){ ^^^^ for(int j=0;j<N;j++){ ^^^^ a[i][j]=rand()%2; cout<<a[i][j]<<" "; } cout<<endl; } 

Must be

 int a[N][M]; for(int i=0;i<N;i++){ ^^^ for(int j=0;j<M;j++){ ^^^ a[i][j]=rand()%2; cout<<a[i][j]<<" "; } cout<<endl; } 

To avoid this kind of error, you can initialize in C ++ and output to the console an array like this, using a range-based loop.

 for ( autp &row : a ) { for ( auto &x : row ) { x = rand() % 2; cout << x << " "; } cout << endl; } 

Keep in mind that the rand function is defined in the <cstdlib> header that should be included in the program.

 #include <cstdlib>