Thursday, April 13, 2017

Dynamic Memory Allocation for Structure


#include <stdio.h>
#include<stdlib.h>

struct book
{
   int id;
   char title[30];
};

int main()
{
   struct book *ptr;
   int i, n;
   printf("Enter number of books: ");
   scanf("%d", &n);

   // Dynamic Memory allocation for n books
   
   ptr = (struct book*) malloc (n * sizeof(struct book));

   for(i = 0; i < n; ++i)
   {
       printf("Enter book ID:");
       scanf("%d", &(ptr+i)->id);
       printf("Enter book Title:");
       scanf("%s", &(ptr+i)->title);
   }

   printf("\nBook Details(ID, Title):\n");

   for(i = 0; i < n ; ++i)
       printf("%d, %s\n", (ptr+i)->id, (ptr+i)->title);

   return 0;
}

Output of Program

Enter number of books: 3
Enter book ID:101
Enter book Title:Computer
Enter book ID:102
Enter book Title:Science
Enter book ID:103
Enter book Title:Security

Book Details(ID, Title):
101, Computer
102, Science
103, Security

No comments:

Post a Comment