×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to demonstrate example structure pointer (structure with pointer) using user define function

In the last program, there was a program to demonstrate example of structure pointer. In this program, we will learn how to create a user define function that will take the structure pointer in C language?

C - structure with pointer using user define function example

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

C Structure & Union Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.