problem in passing by reference

Hi all,

I have a weird problem in my code.

First let me share a snippet of my code as below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<typename T1, typename T2, typename T3, typename T4, typename T5>
void response(const T1& matA, const T2& matB, const T1& matQ,
              const T3& matR, vector<T4>& x, vector<T5>& u)
{
    T1 areSolu = dare(matA, matB, matQ, matR);
    T3 temp = matB.transpose()*areSolu*matB + matR; // inverse term in RE
    
    for (size_t k = 0; k < x.size(); ++k) {
        u[k] = -temp.inverse() * matB.transpose() * areSolu * matA * x[k];


//   std::cout << u[k] << std::endl; // however from this line the first two of u is correct


        x[k+1] = matA*x[k] + matB*u[k];
   }   // end for
        
}   // end response() 


After I call this function in my main.cpp, I want to display the results. Then I called the following function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template<typename T1>
void display(const vector<T1>& result)
{
   if (result.empty()) {
      cout << "No Results Yet!";
      exit(1);
   }
        
   cout.precision(10);
   cout << std::fixed;
   for (size_t k = 0; k < result.size(); ++k) {
      for (size_t j = 0; j != result[0].size(); ++j) {
         cout << setw(15) << result[k](j) << setw(5);
      }
      cout << k << endl;
   }   // end for
}   // end display() 


The weird thing is, my u is not showing properly. The first two elements of u, i.e., u[0], u[1] are all zeros. From the third element, the results are correct.

Look at my first code snippet, if I print the result of u in response() (see commented line), then the first two elements of u is also correct. So I think my u does change from the very first element.

I initialized my u as all zeros in main.cpp, so I am expecting u to be changed after calling response().

Can somebody please help?

Thanks.
Last edited on
You don't provide enough code or information to really hazard a guess, but you do have undefined behavior in your response function. Line 15 writes to an element of x that doesn't exist when k is x.size()-1.
@cire

Thanks for your reply.

Yes I changed to x.size()-1 and now it works.

But I still dont get it why even in my previous flawed code, still from the third element of u the results are correct.
Topic archived. No new replies allowed.