0

The goal is to allocate a 2d integer array, number of columns and rows are given by user input. But here, the rows must not be of the same size and the user will specify how many elements the individual rows are going to have. (This is the part that i do not understand) Then we'll have to assign values to the array elements by taking user inputs and then print the values. This is what I've come up with thus far. What am I doing wrong and what do I need to change?

    #include<iostream>
using namespace std;

int main() {

   int row,col;

   cout<<"How many rows do you want? ";
   cin>>row;

   cout<<"How many columns do you want? ";
   cin>>col;

   int** arr = new int*[row];

   for(int i = 0; i < row; i++){

        arr[i] = new int[col];
   }

   for(int i = 0; i < row; ++i){
       for(int j = 0; j < col; j++){
           cout<<"R "<<i+1<<" C "<<j+1<<" value: ";
           cin>>arr[i][j];
        }
   }

   cout<<"Output array: \n";
   for(int i = 0; i < row; ++i){
        for(int j = 0; j < col; j++){
            cout<<arr[i][j]<<"\t";
    }
     cout<<endl;
   }
}

Thanks!

2
  • Try using std::vector<T> instead of T* pointing to heap allocated memory: vector allocates and deletes its data automatically, copies itself properly, provides interface for algorithms etc. Commented Feb 3, 2020 at 13:42
  • 1
    Hint: how many times does your current code print "How many columns do you want?", and how many times will it need to print it to prompt "the user" to specify "how many elements the individual rows are going to have" Commented Feb 3, 2020 at 14:23

1 Answer 1

2

I would just use a nested std::vector instead. Also, since you want the size to be different for each row, you'll have to ask the user for every row:

#include <iostream>
#include <vector>

int main() {
    int row;
    std::cout << "How many rows do you want? ";
    std::cin >> row;
    std::vector<std::vector<int>> arr(row); // makes a vector of empty int vectors

    for (int i = 0; i < row; ++i) {
        int col;
        std::cout << "How many columns do you want? ";
        std::cin >> col;
        for (int j = 0; j < col; j++) {
            std::cout << "R " << i + 1 << " C " << j + 1 << " value: ";
            int value;
            std::cin >> value;
            arr[i].push_back(value);
        }
    }

    std::cout << "Output array: \n";
    for (auto &v : arr) {
        for (int &i : v) {
            std::cout << i << "\t";
        }
        std::cout << std::endl;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.