I used following function to read double values from a text file and then convert it into a floating point array, but it ends up with unexpected termination during program running. Can anyone tell me what goes wrong here.
float *readFile_double_to_float(char *fileName, int fileSize)
{
double *array = (double *)malloc(fileSize * sizeof(double *));
float *array_float = (float *)malloc(fileSize * sizeof(float *));
FILE *fp = fopen(fileName, "r");
if (fp == NULL)
{
printf("Error: Cannot open file for reading ===> %s\n", fileName);
exit(1);
};
for (int i = 0; i < fileSize; i++)
{
fscanf(fp, "%lf", array + i);
};
fclose(fp);
for (int i = 0; i < fileSize; i++)
{
array_float[i] = (float)array[i];
};
printf("CHECK VAL DOUBLE TO FLOAT : float: %.20f | double: %.20f\n", array_float[0], array[0]);
printf("FILE READ COMPLETED ===> %s\n", fileName);
free(array);
return array_float;
}
sizeof(double *)is the size of a pointer todouble, not adoublevalue. On e.g. a 32-bit platformsizeof(double)is typically larger thansizeof(double *), which means you won't allocate enough memory.doublearray? Why not read directly into thefloatarray?double *array = (double *)malloc(fileSize * sizeof(double *));andfloat *array_float = (float *)malloc(fileSize * sizeof(float *));1) allocatedoubleorfloatNOTdouble *orfloat *2) the returned type isvoid*which can be assigned to any pointer, Casting just clutters the code and is error prone. 3) always check (!=NULL) the returned value to assure the operation was successful. If not successful (==NULL) then callperror( "malloc failed" );so the user is informed of the problem.