Home Articles C Program to Store Information Using Structures with Dynamically Memory Allocation

C Program to Store Information Using Structures with Dynamically Memory Allocation

SHARE

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

Solution:

#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

Back to Programs list.