Problem
I am getting a C2087 'm': missing subscript
compile error and two C4200 nonstandard extension used: zero-sized array in struct/union
warnings when I try to calculate the determinant of a Matrix recursively.
I have a Matrix class that stores the data of the matrix in a 2D array m
where the size is given from template parameters int rows
and int columns
.
Note: I have looked into another post about missing subscript c++ but it does not exactly answer my question since my 2D array has it's size defined by the template parameters and is not left empty.
Code
Here is my MRE that produces the error, built in Visual Studio 2019:
Matrix.h
#include <iostream>
#include <assert.h>
template <typename T, int rows, int columns>
struct Matrix
{
private:
const int size = rows * columns;
union
{
T m[rows][columns];
T a[rows * columns];
};
public:
Matrix()
{
for (int i = 0; i < size; ++i)
a[i] = T(0);
}
Matrix(T* a_)
{
for (int i = 0; i < size; ++i)
a[i] = a_[i];
}
T& operator[](int index)
{
return a[index];
}
Matrix<T, rows - 1, columns - 1> LaplaceMatrix(int row, int column)
{
Matrix<T, rows - 1, columns - 1> res;
int index = 0;
for (int i = 0; i < rows; ++i)
{
if (i == row)
continue;
for (int j = 0; j < columns; ++j)
{
if (j == column)
continue;
res[index] = m[i][j];
++index;
}
}
return res;
}
T Determinant()
{
assert(rows == columns);
if (rows == 2)
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
T determinant = T(0);
for (int i = 0; i < size; ++i)
{
if (m[0][i] != 0)
{
if (i % 2 == 0)
{
Matrix<T, rows - 1, columns - 1> laplace = LaplaceMatrix(0, i);
T det = laplace.Determinant();
determinant += (m[0][i] * det);
}
else
{
Matrix<T, rows - 1, columns - 1> laplace = LaplaceMatrix(0, i);
T det = laplace.Determinant();
determinant -= (m[0][i] * det);
}
}
}
return determinant;
}
};
Main.cpp
int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Matrix<int, 3, 3> m(a);
Matrix<int, 2, 2> laplace = m.LaplaceMatrix(0, 0);
std::cout << laplace.Determinant() << std::endl;
return 0;
}