I have a C-Programm, which reads a .txt-File, saves every float in an array and then is printing out that array.
My Problem is that when i run the code sometimes the output is correct and sometimes one number is 0.00 instead of the right number. Its always the same number.
I'm using macOS and VSC but I have the same problem when I compile the program in my terminal like this :
gcc -o max maxOfFloats.c
./max
This is my Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
int main(int argc, char *argv[]) {
float *ptr = malloc(9*sizeof(float));
FILE *fptr=fopen("zahlen.txt", "r");
char buffer[255];
int counter=0;
while (fgets(buffer, 255, fptr) != NULL) {
sscanf(buffer, "%f\n", ptr+counter*sizeof(float));
counter++;
}
fclose(fptr);
for (int i=0; i<9; i++){
printf("%.2f\n", *(ptr+i*sizeof(float)));
}
free(ptr);
return EXIT_SUCCESS;
}
this is the .txt-File:
695.40
-3.45
3555.05
344.44
344444.00
34.44
343.44
3444.44
664.44
and this is the wrong output:
695.40
-3.45
3555.05
0.00 ← Wrong Number
344444.00
34.44
343.44
3444.44
664.44
thx people