+ 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
2 Réponses
+ 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!
+ 1
Saint Ignucius thank you very much! That helped me a lot! :)