-4

I ran this on NetBeans 8.2 with Cygwin.

#include <iostream>
#include <cstdlib>

using namespace std;

int main() {
/*****************************************************************************/   

    int i,j=0;
    int a;

    int Mtrz1[1][2] = {0};
    int Mtrz2[1][2] = {0};
    int MtrzR[1][2] = {0};
    int MtrzA[1][2] = {0};

/******************************************************************************/   

    for (i=0 ; i<2 ; ++i){
        for (j=0 ; j<3 ; ++j){
            Mtrz1[i][j]=(rand() % 10);
        }
    }

    for (i=0 ; i<2 ; ++i){
        for (j=0 ; j<3 ; ++j){
            cout << Mtrz1[i][j] << " ";
            fflush;
        }
        cout << " " << endl;
    }

    cout << " " << endl;

    /* Here, for some kind of reason [0][2] and [1][0] of 
    MtrxB seem to be getting the same value */ 

    for (i=0 ; i<2 ; ++i){
        for (j=0 ; j<3 ; ++j){
            Mtrz2[i][j]=((j*3)+(9*i)+10);
            /* The formula here is because it did not read the value of any
               variable I passed to it */ 
        }
    }

    for (i=0 ; i<2 ; ++i){
        for (j=0 ; j<3 ; ++j){
            cout << Mtrz2[i][j] << " ";
            fflush;
        }
        cout << " " << endl;
    }
    return 0;
}
  • See here please: https://stackoverflow.com/questions/1108780/why-do-i-always-get-the-same-sequence-of-random-numbers-with-rand –  Feb 02 '18 at 21:50
  • `fflush;` does nothing. Anyways, use `std::flush`. – LogicStuff Feb 02 '18 at 22:03

2 Answers2

3

The dimension in the declaration of an array specifies the number of elements, not the index of the last element.

In:

int Mtrz1[1][2] = {0};

you declare a 1×2 array. In:

for (i=0 ; i<2 ; ++i){
    for (j=0 ; j<3 ; ++j){
        Mtrz1[i][j]=(rand() % 10);
    }
}

You fill in the elements as if it were a 2×3 array. This results in writing to the wrong places, with generally unpredictable behavior, but, apparently in your case, writing to other places in your arrays, and likely to other data in your process.

Change the declarations to specify the dimensions:

int Mtrz1[2][3] = {0};
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

Your array sizes indicate you have one element in your first dimension, and two in your second dimension. You are writing values out of bounds.