简体   繁体   中英

How to generate multiple arrays of random numbers in C

I need to create an array of arrays in C where each array has random values. When I run my code however I get the same set of numbers repeated for each inner array. I've tried to seed inside my inner loop and that is not working for me. How can I generate multiple arrays with random numbers?

int n=100,d=5;
float *p[n];
float arr[d];

srand(time(NULL));
for (int i = 0; i < n; i++){   
    for(int j=0; j<d;j++){
        arr[j] = rand()%100;
    }
    p[i] = arr;
}

It is the pointer to the same array that you save into all elements of p , ie all elements point to arr and thereby the the values from the last loop

You need code like:

int n=100,d=5;
float arr[n][d];

srand(time(NULL));
for (int i = 0; i < n; i++){   
    for(int j=0; j<d;j++){
        arr[i][j] = rand()%100;
    }
}

so that you have a true array of array (aka 2D array), ie float arr[n][d];

Alternatively you can make the array arr using dynamic allocation - like:

int n=100,d=5;
float *p[n];
float* arr;

srand(time(NULL));
for (int i = 0; i < n; i++){   
    arr = malloc(d * sizeof *arr);  // alloc array for this loop
    if (arr == NULL) exit(1);
    for(int j=0; j<d;j++){
        arr[j] = rand()%100;
    }
    p[i] = arr;
}

The second solution is best in case you have large values of n and d (ie to avoid stack overflow)

Seed only once .

You could use a double for loop and two indices to populate your 2D array, like this:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    srand(time(NULL));
    const int n = 100, d = 5;
    float matrix[n][d];
    for (int i = 0 ; i < n ; ++i)
      for(int j = 0; j < d; ++j)
        matrix[i][j] = rand() % 100;
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM