Matrix of any size

I'm trying to write a code where the user inputs the size of the 2-D array and then adds the numbers. If I try it and input for example r=2 and c=3
It doesn't stop taking the inputs.
I would want the matrix to be: 1 2 3
4 5 6

but instead it just keeps letting me put in more rows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

  int r, c, i, j;

  cout<<"How many rows does your matrix have?";
  cin>>r;

  cout<<"How many columns does your matrix have?";
  cin>>c;

  int A[r][c];

  for (i=0; i<r; i++) {
    for (j=0; j<c; j++){
        cin>>A[i][j];
    }
  }

 for (i=0; i<r; i++) {
    for (j=0; j<c; j++){
        cout<< A[i][j];
    }
  }
Last edited on
Why doesn't your code seem to be working? You need to describe the problems.

By the way array sizes in C++ must be compile time constants. If you need run time sized "arrays" I suggest you consider std::vectors instead of arrays.


closed account (E0p9LyTq)
For run time sizing of a multi-dimensional container you can use a vector:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <vector>

int main()
{
   size_t row_size = 4;
   size_t col_size = 3;

   // or let the user supply row and column size

   // a multidimensional vector of a set size
   std::vector<std::vector<short>> aVector(row_size, std::vector<short>(col_size));
   aVector = { { -501, 206, 2011 }, { 989, 101, 206 }, { 303, 456, 596 }, { 123, 543, 108 } };

   for (size_t row = 0; row < row_size; row++)
   {
      std::cout << "Row " << row << ": ";
      for (size_t col = 0; col < col_size; col++)
      {
         std::cout << aVector[row][col] << ' ';
      }
      std::cout << '\n';
   }
   std::cout << '\n';

   // with an initializer list creating a multidimensional vector is easy
   std::vector<std::vector<short>> myVector = { { -501, 206, 2011 }, { 989, 101, 206 }, { 303, 456, 596 }, { 123, 543, 108 } };

   for (size_t row = 0; row < row_size; row++)
   {
      std::cout << "Row " << row << ": ";
      for (size_t col = 0; col < col_size; col++)
      {
         std::cout << myVector[row][col] << ' ';
      }
      std::cout << '\n';
   }
}
Last edited on
closed account (E0p9LyTq)
Boost also provides a multidimensional array library.
http://www.boost.org/doc/libs/1_66_0/libs/multi_array/doc/user.html
Topic archived. No new replies allowed.