C Program to Store and Display Information Using Structures with Pointers

1. Introduction

In the C programming language, structures are used to group together different variables of diverse data types. Using pointers with these structures further enhances their utility by allowing for dynamic memory allocation, efficient passing to functions, and more. This tutorial will showcase how to use pointers with structures to store and display information.

2. Program Overview

1. Define a structure named Person to store information like name and age.

2. Declare a pointer to this structure.

3. Dynamically allocate memory for this structure using malloc.

4. Input details of a person.

5. Display the entered details.

6. Finally, free the dynamically allocated memory.

3. Code Program

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

// Define a structure named 'Person'
struct Person {
    char name[50];
    int age;
};

int main() {
    // Declare a pointer to 'Person'
    struct Person *personPtr;

    // Allocate memory for 'Person' structure
    personPtr = (struct Person*)malloc(sizeof(struct Person));

    // Check for successful memory allocation
    if(personPtr == NULL) {
        printf("Memory allocation failed.");
        return 1;
    }

    // Input details
    printf("Enter name: ");
    gets(personPtr->name);  // Using arrow operator with pointer to access structure members
    printf("Enter age: ");
    scanf("%d", &personPtr->age);

    // Display the details
    printf("\nEntered Details:\n");
    printf("Name: %s\n", personPtr->name);
    printf("Age: %d\n", personPtr->age);

    // Free allocated memory
    free(personPtr);

    return 0;
}

Output:

Enter name: John Doe
Enter age: 28

Entered Details:
Name: John Doe
Age: 28

4. Step By Step Explanation

1. A struct named Person is defined to represent an individual's basic details, containing a string for the name and an integer for the age.

2. We declare a pointer personPtr of type Person.

3. Memory for the Person structure is dynamically allocated using the malloc function.

4. We then check if the memory allocation was successful.

5. The user is prompted to input the name and age of a person. Here, we utilize the arrow (->) operator with the pointer to access and modify the members of the structure.

6. The details entered by the user are displayed.

7. Finally, to prevent memory leaks, we free the memory that was dynamically allocated using the free function.

Comments