0

this is probably a really basic C++ question but I'm very new to C++ so your patience and help is appreciated.

I'm not quite sure why the following code is unable to print out the content of the matrix. I should mention that the variable K is the integer 3.

std::vector<uint8_t> enc_matrix;

for(size_t i = 0; i != K; ++i) {
  enc_matrix[i*(K+1)] = 1;
  cout << "enc_matrix: " << enc_matrix[i*(K+1)] << endl;
  // cout << enc_matrix.at(i*(K+1)) //doesn't show anything either
  cout << "i: " << i*(K+1) << endl;
}

For whatever reason nothing gets printed for enc_matrix[i*(K+1)] but the result of i*(K+1) does get printed. Below is what gets printed:

enc_matrx: 
i: 0
enc_matrx: 
i: 4
enc_matrx: 
i: 8

I'm not sure if it has anything to do with the type of the matrix so I've included the additional info below:

typeid(enc_matrix[0]).name() => h and

typeid(enc_matrix).name() => St6vectorIhSaIhEE

Why is it that enc_matrix doesn't get printed? I am expecting to see 1 assigned to it when i equals to 0, 4 and 8. Thank you.

Mark
  • 730
  • 1
  • 8
  • 22
  • 1
    `enc_matrix` is empty. Indexing into it is undefined behavior, which means anything can happen. – cigien May 02 '21 at 23:41
  • Sorry I'm a little confused if ```enc_matrix``` is empty doesn't that mean ```enc_matrix[i*(K+1)] = 1;``` should fail? In the case that it doesn't fail, is there actually content in that index of the vector? – Mark May 02 '21 at 23:47
  • Please read the linked target. It explains clearly that *anything* can happen when you index into an invalid location, including the program appearing to work. – cigien May 02 '21 at 23:50
  • Read, after casting ```enc_matrix``` to ```unsigned``` and I can now see the values – Mark May 02 '21 at 23:51
  • A bit of useful reading about [Undefined behavior](https://en.cppreference.com/w/cpp/language/ub). This is the Nasal Demons stuff you may have heard about. – user4581301 May 02 '21 at 23:51
  • Casting to `unsigned` allows you to see values, but pay close attention to the other link: Those values don't really exist, so reading or writing them is not a good idea. Right now you see what you expected to see. You might not later. – user4581301 May 02 '21 at 23:55
  • Ok thank you, I read into details. – Mark May 02 '21 at 23:57

0 Answers0