You shouldn't use arrays at all but a matrix class. It is very easy to make one and will avoid all kind of lifecycle and other issues. This is after all C++ not C, and as an added benefit you will use the type system. making sure you are not passing random arrays as matrices (or the other way around) when calling functions
#include <vector>
#include <iostream>
#include <stdexcept>
class Matrix
{
public:
Matrix(std::size_t rows, std::size_t cols)
: m_data(rows * cols, 0), m_rows(rows), m_cols(cols)
{
}
Matrix(std::initializer_list<std::initializer_list<int>> init)
{
m_rows = init.size();
m_cols = m_rows ? init.begin()->size() : 0;
m_data.reserve(m_rows * m_cols);
for (const auto& row : init) {
if (row.size() != m_cols) {
throw std::invalid_argument("All rows must have the same number of columns");
}
m_data.insert(m_data.end(), row.begin(), row.end());
}
}
int& at(std::size_t row, std::size_t col)
{
if (row >= m_rows || col >= m_cols) {
throw std::out_of_range("Matrix::at: index out of bounds");
}
return m_data.at(row * m_cols + col);
}
const int& at(std::size_t row, std::size_t col) const
{
if (row >= m_rows || col >= m_cols) {
throw std::out_of_range("Matrix::at: index out of bounds");
}
return m_data.at(row * m_cols + col);
}
std::size_t rows() const { return m_rows; }
std::size_t cols() const { return m_cols; }
private:
std::vector<int> m_data;
std::size_t m_rows;
std::size_t m_cols;
};
// And this is how you pass a Matrix to a function that prints it
std::ostream& operator<<(std::ostream& os, const Matrix& mat) {
for (std::size_t i = 0; i < mat.rows(); ++i) {
for (std::size_t j = 0; j < mat.cols(); ++j) {
os << mat.at(i, j) << ' ';
}
os << '\n';
}
return os;
}
int main()
{
Matrix matrix{ {1, 2}, {3, 4} };
std::cout << matrix;
return 0;
}
https://onlinegdb.com/jERaNCQ-zX
new: https://stackoverflow.com/questions/35532427/how-to-dynamically-allocate-arrays-in-c.inputMatrix(matrix[n][n])tries to pass a single but non-existent element ofmatrixtoinputMatrix(). Simply evaluatingmatrix[n][n]gives undefined behaviour. And (probable reason for at least one compilation error) its type is not the type thatinputMatrix()expects.