samedi 28 avril 2018

Segmentation fault when generating doubles with rand() in c

Accoring to gdb this line causes a segmentation fault

((double) rand()/(double) (RAND_MAX)) * (r*2)

but this is completely fine

((float) rand()/(float) (RAND_MAX)) * (r*2)

I can make do with floats, but this bugs me. Am I doing something wrong or is rand() incapable of dealing with doubles.

Notice that in the context of upper example all floats are doubles

struct cord {

    float x;
    float y;
};

int main() {

   float r = 3.0;
   int amount = 1000000;

   srand(time(NULL));

   struct cord cords[amount];

   for (int i = 0; i < amount; i++) {

     cords[i] = (struct cord) {
  ->     ((float) rand()/(float) (RAND_MAX)) * (r*2),
         ((float) rand()/(float) (RAND_MAX)) * (r*2)
     };
   }
 ...




Aucun commentaire:

Enregistrer un commentaire