Help me with Array of structs-where is the error?

Discussion in 'C' started by paula_m, Sep 3, 2010.

  1. paula_m

    paula_m New Member

    Joined:
    Sep 3, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hello, I just starting with C and I am having a problem that I can´t understand. Here is the code:


    Code:
    FILE *M;
    M=fopen( "m", "r");
    char line [ 540 ];
    long int i=0;
    struct estr_reg {
           char *molid;
           char *molc;
    };
    struct estr_reg reg[6];
    
    while ( fgets ( line, sizeof line, M ) != NULL )
    {
           reg[i].molid=strtok(line,";");
           reg[i].molc=strtok(NULL,";");
           i++;
    };
    fclose ( M );
    printf("%s %s", reg[0].molid,reg[1].molid);
    return 0;
    }
    
    the problem is that the output of this printf is always "5 5" that is the value of reg[6].molid (the last element of reg). If I do the printf inside the "while (fgets...", the value displayed is correct. But outside the while, it is as if all the elements of the array collapse into one (the last one). Why is this???????

    Thanks!!!
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice