user2999132
user2999132

Reputation:

Multi Dimension Arrays issue

OK so basically i want this code to get the user to input a value each time into the array and they get to specify the amount of rows and columns. I think i that the problem is that each time the user enters the value it goes into the correct column but also into both rows so by the end it only prints out the last lot of numbers the user had entered in all of the rows.

Sorry if that was hard to understand as this is my first post to this site and as you can probably tell i am only learning c++. So if you could help it would be greatly appreciated.

#include <iostream>

using namespace std;

int main()
{
    int row;
    int column;
    int value[row][column];
    cout << "How Many Rows?\n";
    cin >> row;
    cout << "How Many Columns\n";
    cin >> column;
    for(int x = 0; x<row; x++) {
        for(int y = 0; y<column; y++) {
            cout << "Enter Value Now\n";
            cin >> value[x][y];
        }
        cout << endl;
    }
    cout << endl;
    for(int a = 0; a < row; a++) {
        for(int b = 0; b < column; b++) {
            cout << value[a][b] << " ";
        }
        cout << endl;
    }
}

Upvotes: 1

Views: 58

Answers (1)

simonc
simonc

Reputation: 42165

int value[row][column];

declares an array whose dimensions are based on 2 uninitialised values.

If you don't have to use a C-style array, you could use

std::vector<std::vector<int>> value;

and choose its dimensions based on user input.

Alternatively, you could continue to use a C-style array if you allocate it like

int** value;
// input row/column
value = new int*[row];
for (int i=0; i<row; i++) {
    value[i] = new int[column];
}

If you use the latter approach, make sure to also delete all dynamically allocated memory later.

Upvotes: 5

Related Questions