-1

In C++ using Eigen library writing the following example:

#include <iostream>
#include <eigen3/Eigen/Core>

using namespace Eigen;
using namespace std;

int main()
{
    Matrix3f mat;
    Matrix3f m[11];

    cout << mat << endl;
    cout << "\n" << m[11] << endl;
}

The first cout outputs:

-37392.8        4.57244e-41    -37378.8
4.57244e-41    -37206.4         4.57244e-41
-37223.2        4.57244e-41     8.40779e-45

The second one outputs:

           0 -2.51418e-31            0
 2.96401e+17 -1.10025e+33   2.9625e+17
 3.06324e-41            0  3.06324e-41

What does [ ] operator do? How mat[value] is different from mat? Another question :p why Eigen generates extremely large or small numbers, are they random?

P.S: on the second output, the zeros are always zeroes but the other numbers are changing

2 Answers2

3

The declaration

Matrix3f m[11];

doesn't have much to do with Eigen. It's a plain raw array on the stack with 11 instances of Eigen::Matrix3f. And when you

cout << "\n" << m[11] << endl;

this is undefined behavior because you have an out of bounds index. m has 11 elements in total, and as indices start at 0 in C++, the last valid object in m is m[10]. Undefined behavior means your program could do anything - you should hence not try to interpret these results.

That being said, the first cout part is likely to be unaffected by the following UB. It shows the uninitialized values of the Eigen matrix.

lubgr
  • 37,368
  • 3
  • 66
  • 117
2

This is not operator[]. This is a C-style array.

int a[42];

defines an array of 42 ints named a.

In the same line, for a type T and positive integer N, this:

T bla[N];

defines an array of N objects of type T.

So your code

Matrix3f m[11];

defines an array of 11 Matrix3f objects.

The array indexing starts from 0, so the last valid index is 10, not 11 as in your code. Due to Eigen not zero-initializing its objects, you would get random numbers when printing the values of the 0-10th elements.

rubenvb
  • 74,642
  • 33
  • 187
  • 332