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:
readItem
Function:Takes a structure pointer of type
Item
as a parameter.Allocates memory for the
itemName
pointer.Reads product name, price, and quantity from the user and stores them in the passed-in structure.
printItem
Function:Takes a structure pointer of type
Item
as a parameter.Prints the contents of the structure, including product name, price, quantity, and total amount.
In the main
function:
Declare an
Item
structure and a pointer to theItem
.Allocate memory for the
itemName
pointer.Pass the
Item
pointer to both thereadItem
andprintItem
functions.Finally, free the allocated memory for the
itemName
pointer.
Algorithm
Declare a structure
Item
with the required members.Implement the
readItem
function:Allocate memory for the
itemName
pointer.Read product name, price, and quantity from the user.
Store the input values in the passed-in structure.
Implement the
printItem
function:Print the product name, price, quantity, and total amount.
In the
main
function:Declare an
Item
structure and a pointer to theItem
.Allocate memory for the
itemName
pointer.Pass the
Item
pointer to thereadItem
function.Pass the
Item
pointer to theprintItem
function.Free the allocated memory for the
itemName
pointer.
Program
Explanation
The
Item
structure is defined with the necessary members.The
readItem
function allocates memory foritemName
and reads user input.The
printItem
function displays the contents of the structure.In the
main
function, anItem
structure and a pointer toItem
are declared.Memory is allocated for the
itemName
pointer.The
Item
pointer is passed to both thereadItem
andprintItem
functions.Finally, the allocated memory for
itemName
is freed.