c - Random number generation code not working [Probably a stack overflow] -


this c code should generate 1 million random numbers. used srand() t aid pseudrandom generation problem when compiling code multiple times. think theoretically code should work seems misses might causing overflow. idea why stop working during execution process?

#include <stdio.h> #include <stdlib.h> #include <time.h>  int main() {     file *ofp;     int k=0, i=1000000;;     int array[i];      ofp=fopen("output.txt","w");     while (ofp==null)     {         printf("file corrupted or not exist, \nplease create or fix file , press enter proceed");         getchar();     }      srand(time(null));     rand();      (k=0;  k<1000000; k++)     {         array[k] = rand()%100;         fprintf(ofp, "%d\n", array[k]);     }      return 0; } 

fix code following:

// ... #define max 1000000 // ...  int main() {  int array[max];   // proper static allocation  // ...  if (ofp == null) { // while loop has no meaning in here   // ...  }   // ...    return 0;   } 

and not forget close opened streams after you're done them release allocated resources system (in case process terminated anyway, it's ok if did not bother close it)

edit: according c99 spec, allows types used initialize statically allocated arrays, c89 not. furthermore, avoid possible stack overflow issues, try allocate array dynamically in code calling malloc or calloc functions. example:

 // ...  #include <stdlib.h>  // ...  int main()  {  // ...  int* array = malloc(sizeof(int) * i);   // ...  free(array); // don't forget free after you're done.    return 0;   } 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -