I am trying to output uniform numbers into another file and it runs into segmentation faut on the bolded line below.. Maybe it runs out of memory?.? or is it just too much looping and functions around?.?
----------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
main(){
double *x, rst[1];
unsigned int n, i;
double *dmalloc(unsigned int);
void MCG(double *, unsigned int);
void CatFO(double *, unsigned int, double *);
void outputdata(double *, unsigned int);
char ans;
printf("Enter the number of uniform number you want to generate: ");
scanf("%u", &n);
x=dmalloc(n);
MCG(x,n);
for(i=0;i<n;i++){
printf("%2.10f ", x[i]);
}
CatFO(x,n,rst);
printf("\n\n The mean is %10.10f, and the variance is %10.10f\n\n", rst[0],rst[1]);
printf("\n Would you like to save the random numbers to a file (Yes -> y, No -> else)? :");
scanf("%s", &ans);
if (ans == 'y' || ans == 'Y'){
outputdata(x,n);}
}
void outputdata(double *x, unsigned int n){
unsigned int i;
FILE *outfile;
char filename[FILENAME_MAX];
printf("\n What is the name of the file? : ");
scanf("%s", &filename);
outfile = fopen(filename, "w");
if (outfile == NULL){
printf("Can't open output file!\n");
exit(1);
}
for (i=0;i<n;i++){
fprintf(outfile, "%2.10f ", x[i]);
}
fclose(outfile);
}
void MCG(double *x, unsigned int n){
unsigned int i, y , a = 572629L , m= UINT_MAX;
y = a * (m-1)/2;
for(i=0; i<n; i++){
y = a*y ;
x[i]= (double)y /((double)m + 1) ;
}
}
double *dmalloc(unsigned int n){
double *x;
x = (double *)malloc((unsigned int)(n*sizeof(double)));
if (x==NULL){
printf("\nError: couldn't allocate %u double\n",n);
exit(1);
}
return(x);
}
void CatFO(double *x, unsigned int n, double *rst){
unsigned int i;
rst[0]=0., rst[1]=0.;
for(i=0; i<n; i++){
rst[0] += x[i]-x[0];
rst[1] += (x[i]-x[0])*(x[i]-x[0]);
}
rst[1] = (rst[1]-rst[0]*rst[0]/(double)n)/(double)(n-1);
rst[0] = rst[0]/(double)n + x[0];
}