Something that puzzles me in the following simple program:
#include <iostream>
using namespace std;
int main()
{
int row;
cout << "enter row: ";
cin >> row;
int K[row], m[row][5];
cout << "Enter all the " << row << " K values:\n";
for (int i=0;i<row;i++)
cin >> K[i];
cin.ignore(10,'\n');
cout << "1st verification: K[0]=" << K[0] << endl << endl; //1st verification of K[0]
for (int i=0,j=0; i<row,j<5; i++,j++)
{
m[i][j]=2;
cout << "2nd verification: K[0]=" << K[0] << endl; //2nd verification of K[0] (watch: diffferent from above when row=4)
}
cin.get();
return 0;
}
The puzzle is, when the input value for "row" is 4 (other values seem to pose no problem), then in the 2nd verification of the K[0] value (run 5 times, the last time the K[0] will be DIFFERENT from before!--even though it's not changed anywhere: Output (Notice the last line, K[0] is no longer 10):
enter row: 4
Enter all the 4 K values:
10 20 30 40
1st verification: K[0]=10
2nd verification: K[0]=10
2nd verification: K[0]=10
2nd verification: K[0]=10
2nd verification: K[0]=10
2nd verification: K[0]=2
Note if
m[i][j]=2;
is changed to something not involving the indices, it's fine.
Also, if, instead of the short cut simultaneous loop
for (int i=0,j=0; i<row,j<5; i++,j++)
we use nested loop
for (int i=0;i<row;i++)
for (int j=0;j<5;j++)
it's also fine.
So what is the problem, and why does it have problem only for input value row=4, not row=3 or 5 or other values?
Thanks in advance for solving the puzzle for me.