C : Unable to assign a string of a struct to an array

The problem is due to autor being a NULL pointer:

buecher[*num_buch].autor            = NULL;

followed by an attempt to store through it:

buecher[*num_buch].autor->name      = strdup(str1);

This attempts to set the name field of the Autor structure pointer to by autor. But that is just a NULL pointer, and there is no Autor structure, hence no name field to store to.

You can fix it by changing the first assignment to:

buecher[*num_buch].autor            = malloc(sizeof(Autor));

It would also be good practice to check the value returned by malloc to make sure it isn’t NULL.

Don’t forget that you later need to free the storage returned by malloc, strdup, etc. to avoid memory leaks.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top