MARCO LAGALLA
MARCO LAGALLA

Reputation: 257

C List of structs from file

I have a text file with an easy structure:

Foo Bar C
Joe Bob A
.....

And I would like to read the file and populate a "matrix" of structs, let's say a list of pointers to that structs. I have tried:

typedef struct Test
{
    char *A;
    char *B;
    char Res;
}Test;

int main()
{
    
    FILE *fptr;
    int i;
    char A[10], B[10], res;
    
    Test **data = malloc(5*sizeof(Test);
     
    // allocate mem for each Struct
    for(i=0; i<5; i++){
        data[i] = malloc(sizeof(Test));
    }


    fptr = fopen("dati.txt", "r");
    
    // let's say we have 5 records
    for(i=0;i<5;i++) {

        fscanf(fptr,"%s %s %c\n", &A, &B, &res);
        
        data[i]->A = A;
        data[i]->B = B;
        data[i]->Res = res;
        
        printf("\A: %s, B: - %s --> %d", data[i]->A, data[i]->B, data[i]->Res);
    }

    return 0;
}

But if I try to read with a for, I can't read the correct values. What I am missing?

Thank you

Upvotes: 0

Views: 101

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

Your data[i]->A = A; are pointers. When you assign A to it, you assign the pointer, whose data is overwritten each time you read a record from the file.

You must allocate memory for the data read and then copy the data to the new memory, for example:

data[i]->A = malloc(strlen(A)+1);
strcpy(data[i]->A,A);

Upvotes: 1

Related Questions