Search code examples
cstructfgetsscanf

fgets and sscanf with a struct causing unexpected results


I have a program I am writing in which I need to fgets a line from a flat file. I then sscanf the line to put the data into a struct. This gives me very unexpected results. First this is a working example similar to what I would like to do. I have a file department.in which looks like the following:

0 something
1 else
2 more

Here is an example program which runs and gives me the results I would expect:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{

    FILE *in;
    in = fopen("department.in", "r");

    char * buffer = malloc(256 * sizeof(char));
    while((fgets(buffer, 256, in)) != NULL){

            int index;
            char* name;
            sscanf(buffer, "%d %s", &index, name);

            printf("\n\nIndex: %d, Name: %s.\n\n", index, name);
    }

    free(buffer);

    return 0;
}

As expected the results of this are:

Index: 0, Name: something.

Index: 1, Name: else.

Index: 2, Name: more.

However, when I add a struct, it compiles fine:

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int index;
    char* name;
}test;

int main(void)
{

    FILE *in;
    in = fopen("department.in", "r");

    char * buffer = malloc(256 * sizeof(char));
    while((fgets(buffer, 256, in)) != NULL){

            test *mytest = malloc(sizeof(test));

            sscanf(buffer, "%d %s", &mytest->index, mytest->name);

            printf("\n\nIndex: %d, Name: %s.\n\n", mytest->index, mytest->name);
            free(mytest);
    }
    free(buffer);
    return 0;
}

The results are not what I would expect:

Index: 0, Name: (null).

Index: 1, Name: (null).

Index: 2, Name: (null).

Obviously I am doing something wrong with my char's but I for the life of me cannot figure out what. When I change certain things it will seg fault even. Any help would be greatly appreciated!

P.S. This is not homework. I have just made a much more simplified example of my actual code for ease of reading and compiling here as well as to just learn this concept I need. Thanks again!


Solution

  • Assign storage to mytest->name. The output tells you the pointer is NULL.

    mytest->name = malloc(256); /* sizeof(char) is always 1, by definition */
    

    Or you can replace the pointer with an array.

    typedef struct{
        int index;
        char name[256];
    }test;
    

    BTW, good job making a simplified example.