Home »
C programs »
C structure & union programs
C program to demonstrate example of structure pointer (structure with pointer)
In this program, we will learn how to use structure with the pointers? How to declare a structure pointer (pointer to structure object), how to assign values to the structure members and how to access them using structure pointer?
C - Structure with pointer example
In this example, we are implementing a structure item, declaring structure pointer pItem and by using pItem, we will assign and access the elements of the structure.
/* C program to demonstrate example of structure pointer
(structure with pointer)*/
#include <stdio.h>
struct item {
char itemName[30];
int qty;
float price;
float 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 values using pointer*/
printf("Enter product name: ");
gets(pItem->itemName);
printf("Enter price:");
scanf("%f", &pItem->price);
printf("Enter quantity: ");
scanf("%d", &pItem->qty);
/*calculate total amount of all quantity*/
pItem->amount = (float)pItem->qty * pItem->price;
/*print item details*/
printf("\nName: %s", pItem->itemName);
printf("\nPrice: %f", pItem->price);
printf("\nQuantity: %d", pItem->qty);
printf("\nTotal Amount: %f", pItem->amount);
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
C Structure & Union Programs »