Unableto find mistake please help; i am just trying to print 2d array

#include<bits/stdc++.h>
using namespace std;
int main()
{
int i,j,n,T,t,a[n][n];
cin>>T;
for(t=0;t<T;t++)
{
cin>>n;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<a[i][j];
}
}
}
return 0;
}

in the 5th line you have declared the 2-d array as a[n][n], which is incorrect because the variable n is not assigned any value yet, so the 2-d array will not be allocated memory as you wished…
correction : declare the 2-d array after you get the value of n…
int n;
cin >> n;
int a[n][n];

: )

2 Likes

For declaring an array according to input size, which is variable, we need dynamic memory allocation. Declaring array as a[n][n], where n is a constant is static allocation of memory which happens at compile time. It cannot allocate memory according to input size.* In other words, the compiler has to know how much memory we want to allocate before running the program. This has various reasons, for example, the stack memory is very much limited.

If we want to allocate memory according to user input we have to use dynamic memory allocation. It allocates memory on heap which is not fixed. So, large memory can be allocated. Also it needs to be freed after use. In C++, it is provided by new and delete operator. Syntax for this is:
pointer = new data_type;
int *a = new int[4]; // allocates 4 ints and returns ptr to first element.
In C, we have malloc, calloc, for this, also supported by C++.
It is easier to use the vector class for dynamic memory allocation in C++ instead of usual arrays.
vector<int> a(n); // where n is taken as input from user, creates a vector of size n.
You can read about declaring 2D vectors. Vectors are very easy to use.

*The program actually works for smaller value of n given as input. Idk exactly why but it works only for small values of n like upto 1447 on my system. I guess this is because stack has small space. Anyway I would have used vector in that case.

2 Likes

thanks. it worked

thanks. it worked