I have a 2D array which originally looks like the following qrow are defined earlier in my code. I have an input query.txt file, which essentially count the rows of that text file with a loop, and define
int qrow = result of the loop count
This value is not changed later on in the code. Similarly for attrow. In this specific test case,
qrow = 10
attrow = 19
Usage Matrix:
int usage [qrow][attrow];
// Assigned values using a while loop
Usage matrix
0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0
0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0
0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0
1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0
1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0
0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 0
Then I created another array as following:
int aq [qrow][attrow];
I assigned value to aq matrix with another while loop, however I notice if I print out my usage matrix again, values were changed. In specific I found the following example
cout<<"Before, usage[0][7] = "<<usage[0][7]<<endl;
aq[10][9] = 20;
cout<<"After, usage[0][7] = "<<usage[0][7]<<endl;
Output:
Before, usage[0][7] = 1
After, usage[0][7] = 20
Can anyone explain why is this behaving this way? Also appreciate potential resolution to this problem. Thanks!
FYI, below is the actual while loop which is causing this issue,
while(a<qrow){
while(b<attrow){
// Compute A(att=a, q = b)
// initialise aq entry to zero
aq[b][a] = 0;
int use = usage[b][a];
if (use == 0){
aq[a][b] = 0;
b=b+1;
continue;
}
int sum = 0;
int k = 0;
while ( k< freqcol){
double temp = freqMat[b][k];
sum = sum + temp;
k=k+1;
}
aq[b][a] = sum;
b=b+1;
}
a=a+1;
b=0;
}
Usage matrix after loop,
Usage matrix
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 -2147483648 -2147483648
-2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 0
qrow? What isattrow? How are they defined? How are they initialized?int aq [qrow][attrow];-- Ifqrowandattroware notconst, then this is not valid C++. Arrays in C++ must have their size denoted by a constant expression, not a runtime computed value.int aq [qrow][attrow];and use the loopswhile(a<qrow)andwhile(b<attrow). But then you also useaq[b][a] = 0which will work if and only ifqrow == attrow. Otherwise you will go out of bounds and have undefined behavior.std::vectorinstead.