Filling a two-dimensional array with random numbers in c++

An array of random size is created, which is filled with random numbers. For some reason, each line is the same.

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

int main() {
    int m, n;
    float arr[m][n];

    srand(time(0));
    m=3+(rand()%4);
    n=4+(rand()%4);
    //заполнение массива от -10 до 10
    for (int i=0; i<m; i++) {
        for (int j=0; j<n; j++) {
         arr[i][j]=rand() % 21 - 10;
        }
    } 
    //вывод чисел
    cout << "Array: " << endl;
    for (int i=0; i<m; i++) {
        for (int j=0; j<n; j++) {
        cout << arr[i][j] << " ";
        }
        cout << endl;
    } 
    /* проверка размера
    cout << m << endl;
    cout << n << endl; */
    return 0;
}
Author: Range, 2019-03-13

1 answers

First, this code is not compiled. You set the size of a two-dimensional array with variables that are not constants. This will not work, because the size of the static array is determined at the compilation stage.

Secondly, if you still want to set the array dynamically, then you can allocate dynamic memory, thereby creating so-called dynamic arrays. When using dynamic memory, you should not forget about its subsequent release after use, in order to avoid leaks:

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

int main() {
    srand(time(0));

    int m, n;

    m = 3 + (rand() % 4);
    n = 4 + (rand() % 4);
    float ** arr = new float*[m]; // создание динамического двумерного массива на m строк
    for (int i(0); i < m; i++) // создание каждого одномерного массива в динамическом двумерном массиве, или иначе - создание столбцов размерность n
        arr[i] = new float[n];


    //заполнение массива от -10 до 10
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            arr[i][j] = rand() % 21 - 10;
        }
    }
    //вывод чисел
    cout << "Array: " << endl;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

    for (int i(0); i < m; i++) // освобождение памяти каждого одномерного массива в двумерном массиве - удаление столбцов
        delete arr[i];
    delete arr; // освобождение памяти двумерного массива

    return 0;
}
 3
Author: Range, 2019-03-13 23:46:00