'Why pointer to structure element is not working on sscanf?

I need help with a C function I'm trying to do:

#define MAXLEN 128
typedef struct
{
    char *title;
    char *autor;
    int year;
    int num_sh;
    char *sec_sh;
    int flooor;
    char *building;
    char *city;
} book;

void csvToStruct(char *line, book *pBook)
{
    char sec_sh[MAXLEN], title[MAXLEN], autor[MAXLEN], building[MAXLEN], city[MAXLEN];
    int year, num_sh, flooor;
    sscanf(line, "\"%[^\"]\",\"%[^\"]\",%d,%d,\"%[^\"]\",%d,\"%[^\"]\",\"%[^\"]\"",
           title, autor, &year, &num_sh, sec_sh, &flooor, building, city);

    pBook->title = title;
    pBook->autor = autor;
    pBook->year = year;
    pBook->num_sh = num_sh;
    pBook->sec_sh = sec_sh;
    pBook->flooor = flooor;
    pBook->building = building;
    pBook->city = city;
}

I was trying to, instead of asigning my strucure elements values using pBook->element=value, putting pBook->element directly into sscanf. But it isn't working. Why it doesn't work? In my main function, I'm calling csvToStruct in the following way:

int main(void)
{
    book newBook = (book*)malloc(sizeof(book));
    csvToStruct(line, newBook);
};

The line variable is of type char * that I'm getting from a csv file using fgets() function.



Solution 1:[1]

I am going to guess what you old code looked like (its frustrating when you say - "I tried changing this code to something else and it didnt work", but dont show that code you tried).

Anyway you did this (simplifying to one field)

      sscanf(line, "%s",pBook->title);

this doesnt work becuase pbook->title doesnt point to any valid memory to store the data in.

You can do a few things

Reserve space in the book struct

typedef struct
{
    char title[MAXLEN];

} book;

Or you can allocate some heap memory of the correct size so as not to be so wasteful., sadly that is not doable in a one liner because we need to know how big it is.

This is what you must do (your old code was wrong too and will be fixed the same)

 sscanf(line, "%s", title);
 pBook->title = strdup(title);

strdup will allocate memory of the correct size and copy the string into it for you.

Note that you old code was wrong too, becuaseyou set pBook->title to point to stack memory in this function. That memory is released once this function returns.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pm100