1

I want to create a 2d array using random dimensions.

Here's my random number maker method:

int GetRandomNumber(int low, int high)
{
    srand((unsigned)time(NULL));
    int res = rand() % ((high + 1) - low) + low;

    return res;
}

and here's the main code for now:

void main()
{
    int dime = GetRandomNumber(3, 5), a = GetRandomNumber(3, 5), b = GetRandomNumber(3, 5);

    int matA[a][dime];
    int matB[dime][b];

    system("PAUSE");
}

The problem is I get an expression must have a constant value and cannot allocate an array of constant size 0 errors.

My question is how to make a 2d array using random numbers as dimensions.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
mega5800
  • 87
  • 7
  • 1
    if you've tried it, where is the code so we can advise you why your code doesn't work? – Chris Turner Dec 13 '18 at 16:46
  • 1
    Need to see what you tried. – John Bode Dec 13 '18 at 16:48
  • Just one moment please – mega5800 Dec 13 '18 at 16:53
  • 2
    Also read this: [ask] and this: [mcve] – Jabberwocky Dec 13 '18 at 16:56
  • `int dime = GetRandomNumber(3, 5), a = GetRandomNumber(3, 5), b = GetRandomNumber(3, 5); int matA[a][dime]; int matB[dime][b];` – mega5800 Dec 13 '18 at 17:03
  • It seems that you are just looking for a `GetRandomNumber(min, max)` function. Take a look at [this](https://stackoverflow.com/questions/2509679/how-to-generate-a-random-integer-number-from-within-a-range). – Osiris Dec 13 '18 at 17:07
  • GetRandomNumber is a method for picking a random number. my question is how to build an array according to the random numbers from GetRandomNumber – mega5800 Dec 13 '18 at 17:09
  • 1
    It's really frustrating for us when you say "I got an error" but don't tell us which one. There's no way of knowing what the problem is without some kind of diagnostic, so whenever possible show us the code that's broken and the exact error you're getting. Edit your question to include code as necessary, comment-code is much harder to read. – tadman Dec 13 '18 at 17:17
  • you're right, i'll edit it right now – mega5800 Dec 13 '18 at 17:20
  • 1
    @mega5800 please don't put code in comments but [edit] your question and put all clarifications _there_ – Jabberwocky Dec 13 '18 at 17:22
  • @mega5800 ... and where is your `GetRandomNumber` function? – Jabberwocky Dec 13 '18 at 17:23
  • @John Bode check out my question.tnx – mega5800 Dec 13 '18 at 17:28
  • @tadman check out my question.thanks – mega5800 Dec 13 '18 at 17:29
  • @Chris Turner check my question please – mega5800 Dec 13 '18 at 17:29
  • @Jabberwocky please check my question – mega5800 Dec 13 '18 at 17:32
  • 1
    You should move `srand((unsigned)time(NULL));` from the function to `main` and execute it only once, at the beginning, before calling `GetRandomNumber`. Also `void main()` -> `int main(void)` – Bob__ Dec 13 '18 at 17:35
  • 1
    How are you compiling this? If you are using gcc you can invoke with `gcc -std=c99` to allow VLAs, or better: `gcc -std=c99 -Wall -Wextra -Wpedantic` to get some warnings enabled. – ad absurdum Dec 13 '18 at 18:10
  • 1
    @David Bowling i am writing this c program using c++ compiler in VS 17 – mega5800 Dec 13 '18 at 18:17
  • 1
    @mega5800 -- that could be a problem for variable length array solutions. Compile C programs with a C compiler for best results: C and C++ are not the same languages at all, and valid C programs are often not valid C++ programs (or worse, valid but behave differently). I am not sure about the current state of things, but MSVC used to be C89 compliant. I don't think that it ever reached C99 or later compliance, and VLAs were not supported (this may have changed). A dynamic allocation solution like [@JohnBode](https://stackoverflow.com/a/53767547/6879826) may be needed. – ad absurdum Dec 13 '18 at 18:23

3 Answers3

4

As of C99, you can define an array's size at runtime using variable length arrays:

int x = some_value();
int y = some_other_value();

int arr[x][y];

Since their size isn't determined until runtime, there are some restrictions on their use - they can't have static storage duration (i.e., they can't declared at file scope or with the static keyword), and you can't use an initializer in the declaration. You also want to be careful if x or y are large.

If you don't have a C99 or later compiler available, then this won't work. You'll have to use dynamic memory allocation instead, and you'll have to allocate it as a "jagged" array:

int x = some_value();
int y = some_other_value();

int **arr = malloc( sizeof *arr * x );
if ( arr )
{
  for ( size_t i = 0; i < x; i++ )
  {
    arr[i] = malloc( sizeof *arr[i] * y );
  }
}

When you're done, you'd deallocate as

for (size_t i = 0; i < x; i++ )
  free( arr[i] );
free( arr );

This will work like any other 2D array when it comes to accessing elements:

arr[i][j] = some_value();

but be aware that the rows will not be contiguous - there will be gaps from the end of one row to the beginning of the next row. If that matters, then the last option is to declare a 1D array and manually compute the index:

int *arr = malloc( sizeof *arr * x * y );
...
arr[i * x + j] some_value();

When you're done, you'd free it as

free( arr );
John Bode
  • 119,563
  • 19
  • 122
  • 198
0
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int getRandom(int digits, int start) {
    return rand() % digits + start;
}

int main() {
    /* Seed rand() with current time; only want to do
     * this once */
    srand(time(0));

    /* Set row and col sizes equal to random numbers on
     * the interval [1, 4]; 4 is the number of
     * digits we want and 1 is where we start */
    int row = getRandom(4, 1);
    int col = getRandom(4, 1);

    /* Declare a 2d array of row and col size */
    int arr[row][col];

    /* Traverse through the 2d array */
    for(int i = 0; i < row; ++i) {
        for(int j = 0; j < col; ++j) {
            /* Set arr[i][j] to a random number in the
             * interval [-10, 10]; there are 21 digits
             * from -10 to 10 */
            arr[i][j] = getRandom(21, -10);
            /* Print the contents of the array */
            printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
        }
    }

    return 0;
}
Austin Stephens
  • 401
  • 4
  • 9
0
#include <stdio.h>
#include <stdlib.h> 
#include<time.h> 
void main()
{
    srand(time(0));
    int dime = GetRandomNumber(3, 5), a = GetRandomNumber(3, 5), b = GetRandomNumber(3, 5),c = GetRandomNumber(3, 5);

    int matA[a][dime];
    int matB[dime][b];
    printf("%d %d %d %d",dime,a,b,c);    
    //system("PAUSE");
}

int GetRandomNumber(int low, int high)
{
    int res = rand() % ((high + 1) - low) + low;

    return res;
}
Nur Hossen
  • 31
  • 8