I'm writing an exercise on C. I have a struct "testo" with an array of strings and an int.
typedef struct{
char** f;
int n;  }testo;
I have to write a function like this: int carica(char*,testo*) where the string is the name of a file with this format:
n
strin1
...
string n
Then I have to allocate memory for this struct and put every string of the file in the struct so in the end it should be that f[j] is "string j". The return is 0 if everything worked fine or -1,-2,-3,-4 depending on the error that occurs. My function works but then in main it's like I haven't filled the struct.
There is my code:
#include <stdlib.h>
#include <string.h>
typedef struct{
    char** f;
    int n;
}testo;
int carica(char*,testo*);
int main(int argc, char *argv[]) {
    testo* txt;
    carica("prova.txt",txt);
    //mostra(txt);
    return 0;
}
int carica(char* nf,testo* txt){
    FILE* file;
    if( (file = fopen(nf,"r") )==NULL){
        return -1;
    }
    int n_of_strings;
    if(fscanf(file,"%d",&n_of_strings)==EOF || n_of_strings<1){
        return -2;
    }
    getc(file);
    txt = malloc(sizeof (testo) );
    if (txt==NULL)
        return -3;
    txt->n = n_of_strings;
    txt->f = malloc(sizeof(char)*BUFSIZ*n_of_strings);
    char aux[BUFSIZ];
    for(int i=0; i<n_of_strings; i++){
        for(int j=0; aux[j]!='\0';j++)
            aux[j] = '\0';
        fgets(aux,BUFSIZ,file);
        txt->f[i] = malloc(strlen(aux));
        if ((txt->f[i])==NULL)
            return -4;
        strcpy(txt->f[i],aux);
    }
    fclose(file);
    return 0;
}
 
    