1

I am trying to malloc an array of struct pointers (each struct is made by two string) and to fill up the array reading from a txt file which is made like this:

firma1 path1 firma2 path2 firma3 path3 . . .

I get the exception after calling riempi_riga(file_firme[i], f1); I am supposed to pass a single element of my array to the function, but apparently something is not working.

Thanks for help, regards

typedef struct {
    char firma[50];
    char path[100];
}riga;



void riempi_riga(riga*r, FILE* f1) {
    fscanf(f1, "%s ", r->firma);
    fscanf(f1, "%s\n", r->path);
    return;
}
void stampa_riga(riga* r) {
    printf("%s, %s\n", r->firma, r->path);
    return;
}

int num_lines(FILE *f1) {
    char c;
    int lines = 0;
    while ((c = fgetc(f1)) != EOF)
        if (c == '\n')
            lines++;

    if (c != '\n')
        lines++;
    rewind(f1);
    return lines;
}


int main() {

    //riga* r1 =(riga*)malloc(sizeof(riga));
    //printf("%d", sizeof(riga));
    int i = 0;
    FILE* f1;
    f1 = fopen("C:\\Users\\d.foti\\Desktop\\firmaMD5.txt", "r");
        if (f1 == NULL) {
            printf("non sono riuscito ad aprire il file!\n");
            return 0;
            }
        int num_righe = num_lines(f1);
        riga** file_firme = (riga**)malloc(num_righe * sizeof(riga));

        for (i; i < num_lines; i++)
            riempi_riga(file_firme[i], f1);

    //riempi_riga(r1, f1);
    //stampa_riga(r1);
    //fflush(f1);
    if (fclose(f1) != 0)
        printf("non sono riuscito a chiudere il file\n");
    return 0;
}

topo lino
  • 17
  • 3
  • `char c; while ((c = fgetc(f1)) != EOF)` Extremely common FAQ. – Lundin Mar 27 '19 at 13:42
  • 1
    As Lundin says, `EOF` does no fit in a `char` variable and needs an `int` variable. – Paul Ogilvie Mar 27 '19 at 13:43
  • `riga** file_firme = (riga**)malloc(num_righe * sizeof(riga));` This is not how you allocate look-up tables in C. You either need to allocate a 2D array or an array of pointers - this is neither. See [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays). – Lundin Mar 27 '19 at 13:44

0 Answers0