Home c++ Populating a two-dimensional array with C++ random numbers

Populating a two-dimensional array with C++ random numbers

Author

Date

Category

An array of random size is created and filled with random numbers.
For some reason, each line turns out to be the same.

# include & lt; iostream & gt;
#include & lt; cstdlib & gt;
#include & lt; ctime & gt;
using namespace std;
int main () {
  int m, n;
  float arr [m] [n];
  srand (time (0));
  m = 3 + (rand ()% 4);
  n = 4 + (rand ()% 4);
  // filling the array from -10 to 10
  for (int i = 0; i & lt; m; i ++) {
    for (int j = 0; j & lt; n; j ++) {
     arr [i] [j] = rand ()% 21 - 10;
    }
  }
  // display numbers
  cout & lt; & lt; "Array:" & lt; & lt; endl;
  for (int i = 0; i & lt; m; i ++) {
    for (int j = 0; j & lt; n; j ++) {
    cout & lt; & lt; arr [i] [j] & lt; & lt; "";
    }
    cout & lt; & lt; endl;
  }
  / * check size
  cout & lt; & lt; m & lt; & lt; endl;
  cout & lt; & lt; n & lt; & lt; endl; * /
  return 0;
}

Answer 1, authority 100%

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

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

# include & lt; iostream & gt;
#include & lt; cstdlib & gt;
#include & lt; ctime & gt;
using namespace std;
int main () {
  srand (time (0));
  int m, n;
  m = 3 + (rand ()% 4);
  n = 4 + (rand ()% 4);
float ** arr = new float * [m]; // create a dynamic two-dimensional array with m lines
  for (int i (0); i & lt; m; i ++) // create each one-dimensional array in a dynamic two-dimensional array, or otherwise - create columns of dimension n
    arr [i] = new float [n];
  // filling the array from -10 to 10
  for (int i = 0; i & lt; m; i ++) {
    for (int j = 0; j & lt; n; j ++) {
      arr [i] [j] = rand ()% 21 - 10;
    }
  }
  // display numbers
  cout & lt; & lt; "Array:" & lt; & lt; endl;
  for (int i = 0; i & lt; m; i ++) {
    for (int j = 0; j & lt; n; j ++) {
      cout & lt; & lt; arr [i] [j] & lt; & lt; "";
    }
    cout & lt; & lt; endl;
  }
  for (int i (0); i & lt; m; i ++) // freeing the memory of each one-dimensional array in a two-dimensional array - deleting columns
    delete arr [i];
  delete arr; // free the memory of the two-dimensional array
  return 0;
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions