Program: Structure pointers and Functions
Problem Statement
Create a C program that involves structures and pointers. The program should define a structure named Item with members:
itemName(a pointer to a character array)quantity(an integer)price(a floating-point number)amount(a floating-point number, calculated asquantity * price)
The program should have two functions:
readItemFunction:Takes a structure pointer of type
Itemas a parameter.Allocates memory for the
itemNamepointer.Reads product name, price, and quantity from the user and stores them in the passed-in structure.
printItemFunction:Takes a structure pointer of type
Itemas a parameter.Prints the contents of the structure, including product name, price, quantity, and total amount.
In the main function:
Declare an
Itemstructure and a pointer to theItem.Allocate memory for the
itemNamepointer.Pass the
Itempointer to both thereadItemandprintItemfunctions.Finally, free the allocated memory for the
itemNamepointer.
Algorithm
Declare a structure
Itemwith the required members.Implement the
readItemfunction:Allocate memory for the
itemNamepointer.Read product name, price, and quantity from the user.
Store the input values in the passed-in structure.
Implement the
printItemfunction:Print the product name, price, quantity, and total amount.
In the
mainfunction:Declare an
Itemstructure and a pointer to theItem.Allocate memory for the
itemNamepointer.Pass the
Itempointer to thereadItemfunction.Pass the
Itempointer to theprintItemfunction.Free the allocated memory for the
itemNamepointer.
Program
Explanation
The
Itemstructure is defined with the necessary members.The
readItemfunction allocates memory foritemNameand reads user input.The
printItemfunction displays the contents of the structure.In the
mainfunction, anItemstructure and a pointer toItemare declared.Memory is allocated for the
itemNamepointer.The
Itempointer is passed to both thereadItemandprintItemfunctions.Finally, the allocated memory for
itemNameis freed.