0

generate random number 0-1, when I type the input number less than 4, the code works fine. However when the input number above 4, the eclipse stop working. what's wrong with my code

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
double ran(double x0, double x1){
return x0+(x1-x0)*rand()/((double)RAND_MAX);
}
int main(void) {
int a,i;
double *b;
printf("input the size\n");
scanf("%d", &a);
b=(double*)malloc(sizeof(int)*a);
srand((unsigned)time(NULL));
for(i=0;i<a;i++)
{
    b[i]=ran(0,1);
    printf("\n %f", b[i]);
}
free (b);
return 1;

}
user3595689
  • 33
  • 1
  • 6
  • 1
    [don't cast the result of malloc in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – phuclv Nov 01 '14 at 15:14

1 Answers1

1

A double is bigger than an integer. A double is eight bytes, while an integer is 4 bytes. You should replace

b = (double*)malloc(sizeof(int)*a);

with

b = (double*)malloc(sizeof(double)*a);

or even better (thaks to Lưu Vĩnh Phúc)

b = malloc(a * sizeof b[0]);
Community
  • 1
  • 1
Vincent
  • 648
  • 3
  • 9