Nehuy
Nehuy

Reputation: 13

C++ Fill a 2D array with a random int function, where the array is declared by user input

I'm trying to make a C++ program where first the user declare a 2d array, I'm using this:

#include <iostream>
#include <ctime> 
using namespace std;

int main() {
    int i,o; 
    cout << "Ingress rows: ";
    cin >> i; 
    cout << "Ingress columns: "; 
    cin >> o;
    int array1[i][o];
}

So, what I want to do is a function which receives those values and fill the 2d array with random numbers, here is as far as I get (after trying and trying for hours):

void fill_array(int (*arr)[], size_t fila, size_t col) {
    srand(time(NULL));
    for (size_t i = 0; i < fila; i++) {
        for (size_t > j = 0; j < col; j++) {
           arr[i][j] = rand() % 10 + 20;
        }
    }
}

I constantly get the errors:

error: cannot convert 'int ()[o]' to 'int' for argument '1' to 'void fill_array(int, size_t, size_t)' fill_array(array1,i,o);

Any kind of help is more than welcome. Thanks.

Upvotes: 0

Views: 135

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38922

Use vectors. Dynamic arrays int array1[i][o]; are not documented in C++ standard.

...
#include <vector>

void fill_array(std::vector<std::vector<int>> &arr) {
    srand(time(NULL));
    for (size_t i = 0; i < arr.size(); i++) {
        for (size_t j = 0; j < arr[i].size(); j++) {
            arr[i][j] = rand() % 10 + 20;
        }
    }
}

int main() {
    ...
    std::vector<std::vector<int>> array1(i, std::vector<int>(o));
    fill_array(array1);
}

Upvotes: 2

Related Questions