Home C Language Basic C Programs Structures With Dynamically Memory Allocation in C

Structures With Dynamically Memory Allocation in C

Write a C Program to Store Information Using Structures with Dynamically Memory Allocation.

#include<stdio.h>

#include<stdlib.h>

struct item

{

   float Cost,MRP;

   char name[30];

};

int main()

{

   struct item *ptr;

   int i,noOfItems;

   printf(“Enter number of items: “);

   scanf(“%d”, &noOfItems);

   /* Allocates the memory for noOfRecords structures with pointer ptr pointing to the base address.*/

   ptr = (struct item*) malloc(noOfItems * sizeof(struct item));

   for(i = 0; i<noOfItems; i++)

   {

      printf(“Enter name of the Item, Cost and MRP respectively:\n”);

      scanf(“%s %f %f”, (ptr+i)->name, &(ptr+i)->Cost, &(ptr+i)->MRP);

   }

   printf(“Item details as follows:\n”);

   for(i = 0; i<noOfItems ; i++)

      printf(“%s\t%.2f\t%.2f\n”, (ptr+i)->name, (ptr+i)->Cost, (ptr+i)->MRP);

   return 0;

}

Output:

Enter no.of Items: 2

Enter name of the Item, Cost and MRP respectively:

Pen

15

20

Enter name of the Item, Cost and MRP respectively:

Book

36

55

Item details as follows:

Pen        15           20

Book      36           55