I want to write a program to construct a n*n matrix and fill it with 1 to n^2
You can either use a nested standard container or write your own user-defined class modelling a matrix data structure. Also note that there are plenty of linear algebra libraries providing well designed and tested matrix classes.
If you decide to implement one, this may a basic starting point
class Matrix
{
size_t rows_, cols_;
std::vector<int> m_; // Note that this is ONE vector
public:
Matrix() = default;
Matrix(size_t r, size_t c)
: rows_{r}, cols_{c}, m_(r * c)
{}
size_t n_rows() const noexcept {
return rows_;
}
size_t n_columns() const noexcept {
return cols_;
}
// I prefer to overload operator() for matrices, instead of operator[]. We need a little
// formula to calculate the 1D index, given the 2D indices.
auto operator() (size_t r, size_t c) const {
return m_[r * cols_ + c];
}
auto& operator() (size_t r, size_t c) {
return m_[r * cols_ + c];
}
auto begin() {
return m_.begin();
}
auto end() {
return m_.end();
}
// You may want the const version and cbegin(), cend(), too.
// ...
};
Having that, you can complete your task in a couple of ways
// Using a nested loop
Matrix a(n, n);
for (size_t i{}, k{}; i < a.n_rows(); ++i) {
for (size_t j{}; j < a.n_columns(); ++j) {
a(i, j) = ++k;
}
}
// Using std::iota from <numeric> header
Matrix b(n, n);
std::iota(b.begin(), b.end(), 1);
I get a segmentation fault (core dumped). I have no clue why this happens.
Those lines
int n;
cin >> n;
int array[n][n];
Declare a Variable Length Array, which is not a standard compliant container. Some compilers provide theese as an extension. In particular, gcc also has the following documentation (emphasis mine).
6.20 Arrays of Variable Length
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.
Note the use of the automatic term.
In the comments, you say that you are testing the program with a size of 2000, which is probably too big for your environment. See e.g. why is stack memory size so limited?.