+ 1

Structs and pointers

Hello! I have written this code but it doesn't seem to work and I can't figure out why. https://code.sololearn.com/c7EGRMUCwhHZ/?ref=app

19th May 2019, 5:10 PM
MargaritaK
2 Answers
+ 2
Main Issue: In your printf() function you need to de-reference pointer->code and pointer->price to get the actual values that those pointers point to. So printf("%s %s %d %lf\n", pointer->title, pointer->author, ----> *pointer->code, *pointer->price); Other small issues: You don't need to cast the return type of malloc() since void * is automatically promoted to the correct type. If you forget to include <stdlib.h> or if your type changes in the future it can cause some bugs to crop up or even program crashes. :-) One exception to that rule is if you're writing C code that is supposed to be compatible with C++. It's also good practice to check that the return of malloc() isn't NULL. Useful trick: Where you type: pointer = malloc(sizeof(struct book)); You can instead type: pointer = malloc(sizeof(*pointer)); And it'll allocate the sizeof whatever your pointer points to. This can also help defend you from bugs if your variable type changes. Hope that helps!
19th May 2019, 8:48 PM
Komodo64
Komodo64 - avatar
+ 1
Saint Ignucius thank you very much! That helped me a lot! :)
20th May 2019, 7:19 AM
MargaritaK