Problem 1: Order Matters.
int x, y; // x and y have undefined values
int arr[x][y]; // attempts to dimension an array with undefined values.
cout << "Enter row number and column number :";
cin >> x >> y; // now we have x and y values.
Solution:
int x, y; // x and y have undefined values
cout << "Enter row number and column number :";
cin >> x >> y; // now we have x and y values.
int arr[x][y]; // can now dimension array
Problem 2: Non-Standard code
Arrays can only be dimensioned with constant values in Standard C++
int arr[x][y]; // fails on many compilers.
// Don't be angry, they are following the language rules.
There are many reasons for this. The biggest, in my opinion, is they make it hard to control the amount of Automatic Memory being used by the program. Enter 2000 for x
and y
and watch the program fail in interesting and often bizarre ways.
Solution:
Use a std::vector
here.
vector<vector<int>> arr(x, vector<int>(y));
Note:
vector
s of vector
s have poor performance due to low spatial locality. Each vector
contains its own block of storage located somewhere in dynamic memory, and every time the program moves from one vector
to another, the new vector
's data must be looked up and loaded.
If this is a concern, use a single vector
approach like the one described here.
Problem 3: Writing to an input stream
cin >> arr[row][col] << " ";
reads from cin
into arr[row][col] and then attempts to write
" "to the stream.
cin` is input-only and cannot be written to.
Solution:
Since it's likely you do not need this write at all, >>
automatically separates tokens based on whitespace separation, we can safely discard the write.
cin >> arr[row][col];
Problem 4: Writing arrays rather than the data in the array
cout << arr[row] << arr[col] << " ";
writes arr[row]
a row in the array rather than a single data value to cout
. It then writes arr[col]
, another row in the array, to cout
.
Solution:
to write the value at arr[row][col]
, we need to do literally that
cout << arr[row][col] << " ";
I think that about covers it.
Recommended reading
Why is "using namespace std;" considered bad practice?
A good C++ reference text. Whatever you are currently learning from is not doing you any favours.