I'm trying to take the difference of the two rows using the for loop. There are total four rows, so the result would be simply 3 numbers after subtraction and summations. But the loop provide additional results which are unreasonable!! Does anyone know why it happens?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int v[4][3] = {
{1,2,3},
{3,4,5},
{6,7,8},
{9,10,11} };
cout << sizeof(v) << "\n";
float sq = 0;
for(int i = 0; i < 3; i){
for(int j = 0; j < 2; j){
sq = (v[i 1][j] - v[i][j]) (v[i 1][j 1] - v[i][j 1]) (v[i 1][j 2] - v[i][j 2]);
cout << "diff " << sq << endl;
}
}
cout << "final square of the numbers: " << sq << endl;
return 0;
}
``
CodePudding user response:
Access to v
at or past 4 in the first index or 3 in the second is undefined behavior.
If you are lucky, you get nonsense. If you are luckier, your program crashes when you test it. If you are unlucky, the program does any arbitrary action within its power.
In your case, you access up to v[4][5]
.
A programming executing undefined behavior has no constraints put on it by the C language.
When i=3, j=3
, we get:
sq = (v[4][3] - v[3][3]) (v[4][4] - v[3][4]) (v[4][5] - v[3][5]);
and all of those access to v
are illegal as they are past the array bounds in either the first or second dimension, or both.