0

What I try to do is to create a function thay allocates memory for an array and fills it up with random numbers in a specified range(in my case 50-76).srandis in the main and I use the <time.h> header.

unsigned* randomgen(int size, unsigned max, unsigned min)
{
    int i;
    unsigned* arr = (unsigned*)malloc(size * sizeof(unsigned));
    for (i = 0; i < size; i++) {
        arr[i] = (rand() % (max - min + 1)) + min;
        printf("%d ", arr[i]);
    }
    return arr; 
}

I want to get numbers like 60 52 68 .... What is happening is that the numbers generated look something like3526 4582 13224 .... This is only happening in this function.When I do it in main I get the wanted results.

Georgi H
  • 3
  • 2
  • what do you pass to the `randomgen`? and what you do in the `main`? – fas Apr 04 '20 at 15:30
  • I pass the size of the array-size, lower part of the range-min and the upper-max. I thied the code in the function if it worked at all in ```main``` and it did with the resunts I expected – Georgi H Apr 04 '20 at 15:35
  • It works perfectly fine for me. Do you pass in min and max to the right fields? – aeternalis1 Apr 04 '20 at 15:35
  • Thanks for the help it appears that I didn,t pass the arguments in the right order. Thanks a bunch guys. – Georgi H Apr 04 '20 at 15:39
  • Does this answer your question? [C: filling an array with random numbers in a range](https://stackoverflow.com/questions/60931951/c-filling-an-array-with-random-numbers-in-a-range) – Ardent Coder Apr 04 '20 at 17:50

1 Answers1

0

Georgi.

I've made a successfull test with the following code. I think the problem could be a several things, but mainly allocating memory locally instead globally. If this won't help you, I suggest you put here the complete code for your attempt application.

:)

void randomgen(int *intarray, int size, int max, int min)
{
    int i;

    for (i = 0; i < size; i++) {
        intarray[i] = (rand() % (max - min + 1)) + min;
        printf("%d ", intarray[i]);
    }
}
int main(int argc, char **argv){
  int *iA;
  int i;

  if ( (iA = (int*)malloc(20 * sizeof(int))) == NULL ){
    printf("error");
    return 0;
  }
  randomgen(iA, 20, 59, 50);

  for (i = 0; i < 20; i++) {
    printf("iA[%d]=%d\n", i, iA[i]);
  }
  return 0;
}

It produces the following output:

53 56 57 55 53 55 56 52 59 51 52 57 50 59 53 56 50 56 52 56
iA[0]=53
iA[1]=56
iA[2]=57
iA[3]=55
iA[4]=53
iA[5]=55
iA[6]=56
iA[7]=52
iA[8]=59
iA[9]=51
iA[10]=52
iA[11]=57
iA[12]=50
iA[13]=59
iA[14]=53
iA[15]=56
iA[16]=50
iA[17]=56
iA[18]=52
iA[19]=56
rfermi
  • 179
  • 11