Can we malloc structures in c? | Sololearn: Learn to code for FREE!
+ 3

Can we malloc structures in c?

I am working on a CUI library management system in C and I don't know how or can we malloc structures. If we con then how to. If we cannot then alternatives. Here is the code I tried: int num; struct library { ..... }; struct library *a; printf("Enter number of books"); scanf("%d",&num); a = (struct*)malloc(num * sizeof(libary)); thanks in advance.

19th Dec 2020, 4:23 PM
Muzammil
Muzammil - avatar
2 Antworten
+ 6
You can dynamically allocate structures just like built-in types. The problem is your allocation line. Right now you cast the pointer to "struct*", which is not a type and should be "struct library*". Similar with the call to sizeof(), which needs to be "struct library" since you didn't typedef the struct. Therefore the fixed line would be: a = ( struct library* ) malloc ( num * sizeof ( struct library ) );
19th Dec 2020, 4:41 PM
Shadow
Shadow - avatar
+ 2
Thanks shadow for your help.
20th Dec 2020, 11:15 AM
Muzammil
Muzammil - avatar