0

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

user3840170
  • 26,597
  • 4
  • 30
  • 62
chrizzla
  • 53
  • 8
  • 1
    Pointer arithmetics are taking in account the size of the pointee. So your `sizeof` multiplication is not needed (and breaking things for you too). And yes, you can use `ptr[i]` instead for cleaner code. – Eugene Sh. Nov 17 '20 at 17:30
  • thanks it's working now (y) – chrizzla Nov 17 '20 at 19:21

1 Answers1

0

Don't multiply your indexes by the size of an item; pointers do that automatically, which is why they're typed. You're leaping off into uncharted memory waters (and sometimes skipping a spot, which is why the print routine doesn't see the same thing as the population routine). Replace those parts like this:

 sscanf(buffer, "%f\n", &(ptr[counter]));

and

printf("%.2f\n", ptr[i]);

And you should see more consistent results.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175