2

I want to generate x number of random numbers and everything works except it gives me sequenced numbers, not random numbers.

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

int main(){

int x;
printf("How many  elements do you want?\n");
scanf("%d", &x);
int *array = (int *)malloc(x * sizeof(int));
srand(time(NULL));
for(int y = 0; y < x; y++){

    *(array + y) = 2 +  rand() % 99;
}

for(int y = 0; y <x; y++){
    printf("Array element %d: %d\n", y, (*array+ y));

}

return 0;}

It gives the numbers like: 27 28 29 30 31, only the first number is random in each execution, others are sequential.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    [Do I cast the result of malloc?](https://stackoverflow.com/q/605845/2173917) – Sourav Ghosh Jan 30 '19 at 11:58
  • 8
    `*(array + y)` and `(*array + y)` are not the same. If you'd used the common notation `array[y]` this nasty typo probably would not have happened. – alk Jan 30 '19 at 12:01
  • Note that for any pointer or array `p` and index `i`, the expression `*(p + i)` is *exactly* equal to `p[i]`. The latter is generally easier to read, less to write, and also safe from errors like the one you have. – Some programmer dude Jan 30 '19 at 12:03
  • `*(pointer + integer)` is 100% absolutely the same as `pointer[integer]`. Note that using an array identifier in these kind of expressions implicitly converts from array type to pointer type. – pmg Jan 30 '19 at 12:03

1 Answers1

7

Most likely you're printing a wrong value.

You need to change (*array+ y) to *(array+ y) in printf() statement, otherwise, you end up printing the value of the first random number, plus the iteration counter (which explains the output you get).

Just to add some opinionated view: The array indexing operator [] is there, some chose to prefer using it to avoid mistakes just like this. Your statements can be easily re-written to make use of that, like

for(int y = 0; y < x; y++){

    array[y] = 2 +  rand() % 99;
}

for(int y = 0; y <x; y++){
    printf("Array element %d: %d\n", y, array[y]);
}

That said,

  • Please see do I cast the result of malloc?
  • Always check for the success of the called function before using the return value. Check against NULL return of the malloc() call, otherwise you may end up dereferencing NULL, which invokes undefined behavior
alk
  • 69,737
  • 10
  • 105
  • 255
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261