1
   #include <iostream>
   using namespace std;
   void readMatrix(int a[][10], int R, int C){
    for(int i=0; i<R; i++){
        for(int j=0; j<C; j++){
            cin>>a[i][j];
        }
    }
}
void printMatrix(int a[][10], int R, int C){
    for(int i=0; i<R; i++){
        for(int j=0; j<C; j++){
            cout<<a[i][j];
        }
    }
}

int main() {
    int r,c;
    cin>>r>>c;
    int a[][10];
    cout<<"Reading Matrix : "<<endl;
    readMatrix(a, r, c);
    cout<<"Printing Matrix : "<<endl;
    printMatrix(a, r, c);


    return 0;
}

I am trying to read a matrix and then print it. But I am getting this error:

Compiling failed with exitcode 1, compiler output:

prog.cpp: In function `int main()':

prog.cpp:21:9: error: storage size of a isn't known

int a[][10];

Image of error

I am a novice in C++, so please help me debug this.

2 Answers2

0

You need to specify the exact size of the array in this line:

int a[][10];

Since the compiler has no way of knowing. Consider using a std::vector if the size will vary.

Also your code will go out of bounds because the rows and columns that you are taking from the user will not match the rows and columns of the array:

int r,c;
cin>>r>>c;
int a[][10];

You will go out of bounds once you call one of your functions. In order to correct this you should use a vector of vectors (suggested by user4581301 instead of 2d vector) which you can resize to the correct size. Like this:

// Create a vector containing r vectors of size c or another way to thinking about it is
// a 2d vector with r rows and c columns 
vector<vector<int> > vec( r , vector<int> (c));  
bhristov
  • 3,137
  • 2
  • 10
  • 26
  • Minor niggle: `vector > vec( r , vector (c)); ` is not a 2D `vector` It is a `vector` of `vector`s. – user4581301 Jan 03 '20 at 18:59
  • I am a beginner to C++ and just wanted to learn reading and writing elements of the matrices. Check below for what worked for me. – Aman Sawarn Jan 03 '20 at 23:55
0
#include <iostream>
using namespace std;
void readMatrix(int a[][10], int R, int C){
    for(int i=0; i<R; i++){
        for(int j=0; j<C; j++){
            cin>>a[i][j];
        }
    }
}
void printMatrix(int a[][10], int R, int C){
    for(int i=0; i<R; i++){
        for(int j=0; j<C; j++){
            cout<<a[i][j]<<" ";
        }
        cout<<endl;
    }
}

int main() {
    int r,c;
    cin>>r>>c;
    int a[4][10];
    cout<<"Reading Matrix : "<<endl;
    readMatrix(a, r, c);
    cout<<"Printing Matrix : "<<endl;
    printMatrix(a, r, c);


    return 0;
}

It has worked for me. While defining a 2-d array, It is mandatory to specify the size of columns and rows. It worked perfectly fine after defining the number of rows for the array.