-2
int* create_array(char category, int n){
  int *a;

  a = malloc(n* sizeof(int));

  for (int i = 0; i < n; i++) {
    int x;
    srand( time(NULL));
    x = rand();
    a[i] = x;
  }

When I print this code, it just prints the same random variable 'n' times.

naikrima
  • 91
  • 1
  • 1
  • 6
  • 3
    These answers may help: [srand function is returning same values](http://stackoverflow.com/questions/14494375/srand-function-is-returning-same-values/14494428#14494428) and [Why does rand() return the same value using srand(time(null)) in this for loop?](http://stackoverflow.com/questions/10644593/why-does-rand-return-the-same-value-using-srandtimenull-in-this-for-loop/10644601#10644601) – Gomiero Oct 23 '16 at 05:19

2 Answers2

0

You can use srand(getpid() or you can specify ther range of random numbers using x=rand()%11 generates from 0-10;

Anjaneyulu
  • 434
  • 5
  • 21
0

You can try something like this:

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

int *create_array(char category, int n);

int
main(int argc, char const *argv[]) {
    time_t t;
    int *array;
    int i, n;
    char category;

    srand((unsigned)time(&t));

    printf("Enter category: ");
    if (scanf("%c", &category) != 1) {
        printf("Invalid category.\n");
        exit(EXIT_FAILURE);
    }

    printf("Enter n numbers: ");
    if (scanf("%d", &n) != 1) {
        printf("Invalid n value.\n");
        exit(EXIT_FAILURE);
    }

    array = create_array(category, n);

    printf("Your n random numbers between 0-10:\n");
    for (i = 0; i < n; i++) {
        printf("%d ", array[i]);
    }

    free(array);

    return 0;
}

int
*create_array(char category, int n) {
    int *array;
    int i, candidate;

    array = malloc(n * sizeof(*array));

    for (i = 0; i < n; i++) {
        candidate = rand() % 10;
        array[i] = candidate;
    }

    return array;
}   
RoadRunner
  • 25,803
  • 6
  • 42
  • 75