+ 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.
2 Answers
+ 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 ) );
+ 2
Thanks shadow for your help.