I'm working with an old code base that implements a matrix. I'm trying to add a method to enable construction from an initializer list. I'm quite confused because this was working yesterday. I'm not sure what I've changed by this code crashes and burns when it gets to _Array[row * col + col] = r.begin()[col];
. Why can I not access this _Array
?
Heres an abstracted example:
#include <initializer_list>
#include <iostream>
template<class T>
class Matrix {
void resize(unsigned int rows, unsigned int cols) {
if (rows * cols != _Rows * _Cols) {
if (_Array) {
delete[] _Array;
_Array = nullptr;
}
if (rows && cols) {
_Array = new T[rows * cols];
}
}
_Rows = rows;
_Cols = cols;
}
/**
* number of rows
*/
unsigned int _Rows;
/**
* number of columns
*/
unsigned int _Cols;
/**
* pointer to block of memory of the data, stored in row-major format.
*/
T *_Array;
public:
Matrix<T>(std::initializer_list<std::initializer_list<T>> matrix)
: _Array(nullptr) {
_Rows = matrix.size();
_Cols = (*matrix.begin()).size();
resize(_Rows, _Cols);
for (int row = 0; row < _Rows; row++) {
const std::initializer_list<T> &r = matrix.begin()[row];
for (int col = 0; col < _Cols; col++) {
printf("Row: %d; col: %d; value: %d", row, col, r.begin()[col]);
_Array[row * col + col] = r.begin()[col];
}
}
}
};
int main(){
Matrix<int> matrix(
{
{1, 2, 3},
{4, 5, 6},
});
}
clion output:
AddressSanitizer:DEADLYSIGNAL
Row: 0; col: 0; value: 1
Process finished with exit code 6
P.S. I would love to just use STL types but this is not an option and I'm aware of the bad practice of prepending variable names with underscores.