Array in C++ must have a size defined at compile-time.
If you want variable length array, use std::vector instead.
In your case, I would use template for Matrix Size and have different implementation for different matrix size (unless I misunderstood your intentions).
template<int SIZE>
struct Matrix {
std::array<std::array<float, SIZE>,SIZE> m;
std::array<float,SIZE>& operator[](int a) {
if(a>=SIZE) {
throw std::out_of_range("Out of range exception");
}
return m[a];
}
};
template<int SIZE>
void calcMatrix(Matrix<SIZE>& matrixReturnAsArray );
template<>
void calcMatrix<2>(Matrix<2>& matrixReturnAsArray )
{
// Code for 2x2 Matrix
std::cout << "<2>" << std::endl;
std::cout << matrixReturnAsArray[1][1] << std::endl;
}
template<>
void calcMatrix<3>(Matrix<3>& matrixReturnAsArray )
{
// Code for 3x3 matrix
std::cout << "<3>" << std::endl;
std::cout << matrixReturnAsArray[2][2] << std::endl;
}
int main() {
std::array<float,2> a={1,2};
Matrix<2> m2;
m2.m = {a,a};
std::array<float,3> b={1,2,3};
Matrix<3> m3;
m3.m = {b,b,b};
calcMatrix(m3);
calcMatrix(m2);
}
Since I did not defined the generic template, using any other value than 2 or 3 for size will result in an error at compile time.
Edit : Used reference to std::array instead of pointer after @Caleth’s suggestion
Edit 2: Added operator [] for easy access and exception for safety