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 as quantity * price)

The program should have two functions:

  1. 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.

  2. 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 the Item.

  • Allocate memory for the itemName pointer.

  • Pass the Item pointer to both the readItem and printItem functions.

  • Finally, free the allocated memory for the itemName pointer.

Algorithm

  1. Declare a structure Item with the required members.

  2. 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.

  3. Implement the printItem function:

    • Print the product name, price, quantity, and total amount.

  4. In the main function:

    • Declare an Item structure and a pointer to the Item.

    • Allocate memory for the itemName pointer.

    • Pass the Item pointer to the readItem function.

    • Pass the Item pointer to the printItem function.

    • Free the allocated memory for the itemName pointer.

Program

#include <stdio.h>
#include <stdlib.h>

struct Item {
    char *itemName;
    int quantity;
    float price;
    float amount;
};

void readItem(struct Item *itemPtr);
void printItem(const struct Item *itemPtr);

int main() {
    struct Item item;
    struct Item *itemPtr = &item;

    // Allocate memory for the itemName pointer
    item.itemName = (char *)malloc(50 * sizeof(char));

    // Pass the Item pointer to readItem
    readItem(itemPtr);

    // Pass the Item pointer to printItem
    printItem(itemPtr);

    // Free the allocated memory for itemName
    free(item.itemName);

    return 0;
}

Explanation

  • The Item structure is defined with the necessary members.

  • The readItem function allocates memory for itemName and reads user input.

  • The printItem function displays the contents of the structure.

  • In the main function, an Item structure and a pointer to Item are declared.

  • Memory is allocated for the itemName pointer.

  • The Item pointer is passed to both the readItem and printItem functions.

  • Finally, the allocated memory for itemName is freed.