In this example, we have a structure named item with the pointer structure object named pItem, here we are implementing two user define functions readItem() - to read structure members and printItem() - to print the value of structure members.
/*C program to demonstrate example of structure pointer
using user define function*/
#include <stdio.h>
struct item
{
char itemName[30];
int qty;
float price;
float amount;
};
/*readItem()- to read values of item and calculate total amount*/
void readItem(struct item *i)
{
/*read values using pointer*/
printf("Enter product name: ");
gets(i->itemName);
printf("Enter price:");
scanf("%f",&i->price);
printf("Enter quantity: ");
scanf("%d",&i->qty);
/*calculate total amount of all quantity*/
i->amount =(float)i->qty * i->price;
}
/*printItem() - to print values of item*/
void printItem(struct item *i)
{
/*print item details*/
printf("\nName: %s",i->itemName);
printf("\nPrice: %f",i->price);
printf("\nQuantity: %d",i->qty);
printf("\nTotal Amount: %f",i->amount);
}
int main()
{
struct item itm; /*declare variable of structure item*/
struct item *pItem; /*declare pointer of structure item*/
pItem = &itm; /*pointer assignment - assigning address of itm to pItem*/
/*read item*/
readItem(pItem);
/*print item*/
printItem(pItem);
return 0;
}
Output
Enter product name: Pen
Enter price:5.50
Enter quantity: 15
Name: Pen
Price: 5.500000
Quantity: 15
Total Amount: 82.500000
In this example, we have a structure named item with the pointer structure object named pItem, here we are implementing two user define functions readItem() - to read structure members and printItem() - to print the value of structure members.
Output
need an explanation for this answer? contact us directly to get an explanation for this answer