Pointer to Structure

Pointers to Structures in C

In C, a pointer to a structure is a pointer that holds the address of a structure variable.

  • This allows us to access and manipulate structure members using the pointer.

  • Using pointers with structures is especially efficient for large structures, as it avoids copying the entire structure when passing it to functions.


Steps to Create and Use Pointers to Structures

  1. Define a Structure
    Define the structure type with its members.

  2. Declare a Structure Variable
    Create an instance of the structure.

  3. Create a Pointer to the Structure
    Declare a pointer that stores the address of the structure variable.

  4. Access Members
    Use the -> (arrow) operator to access structure members through the pointer.


Example: Declaring a Pointer to a Structure

struct name { int member1; char member2; // ... }; int main() { struct name *ptr; // pointer variable of type struct name }

Here, ptr is a pointer variable of type struct name.


Accessing Structure Members Through a Pointer

A structure's members can be accessed using pointers in two ways:

  1. Referencing the pointer to another address to access memory.

  2. Using dynamic memory allocation to allocate memory and access members.


Accessing Structure Members Through Pointers in C

Pointers to structures allow efficient access and manipulation of structure data. There are two common ways to access structure members using pointers:


1. Referencing Pointer to Another Address

You can point a structure pointer to the memory address of an existing structure variable and access its members using the -> operator or the dereference operator *.

Example:

#include <stdio.h> typedef struct person { int age; float weight; } Person; int main() { struct person person1; struct person *personPtr; personPtr = &person1; // Pointer referencing memory address of person1 // Input data using pointer printf("Enter Age: "); scanf("%d", &personPtr->age); // Using -> operator // or scanf("%d", &(*personPtr).age); // Using dereference operator printf("Enter Weight: "); scanf("%f", &personPtr->weight); // Display data printf("Displaying:\n"); printf("Age: %d, Weight: %.2f\n", personPtr->age, personPtr->weight); return 0; }
  • personPtr->age is equivalent to (*personPtr).age.

  • The pointer points to the structure, and -> accesses its members directly.


2. Accessing Structure Members Using Dynamic Memory Allocation

Memory for structures can be allocated dynamically using malloc(). This is useful for creating arrays of structures at runtime.

Syntax of malloc:

ptr = (cast-type*) malloc(byte-size);

Example:

#include <stdio.h> #include <stdlib.h> struct person { int age; float weight; char name[30]; }; int main() { struct person *ptr; int i, num; printf("Enter number of persons: "); scanf("%d", &num); // Allocate memory for 'num' persons ptr = (struct person*) malloc(num * sizeof(struct person)); // Input data for(i = 0; i < num; ++i) { printf("Enter name, age, and weight of person %d:\n", i+1); scanf("%s %d %f", (ptr+i)->name, &(ptr+i)->age, &(ptr+i)->weight); } // Display data printf("Displaying Information:\n"); for(i = 0; i < num; ++i) printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)->weight); free(ptr); // Free dynamically allocated memory return 0; }
  • (ptr + i)->member accesses the ith structure’s member.

  • Dynamic allocation avoids fixed-size arrays and improves memory flexibility.


Why Use Pointers to Structures?

  • Memory Efficiency: Avoids copying large structures when passing to functions.

  • Dynamic Access: Useful for arrays of structures created at runtime.

  • Flexible Parameter Passing: Pass structure pointers to functions instead of whole structures.


3. Passing a Pointer to a Structure to a Function

Structure pointers are commonly passed to functions to modify the structure’s members directly.

Example:

#include <stdio.h> struct Person { char name[50]; int age; }; // Function to update age void updateAge(struct Person *p, int newAge) { p->age = newAge; // Modify age using the pointer } int main() { struct Person person1 = {"Alice", 25}; printf("Original Age: %d\n", person1.age); // Pass structure pointer to function updateAge(&person1, 30); printf("Updated Age: %d\n", person1.age); return 0; }
  • Passing &person1 allows the function to modify the original structure.

  • Avoids copying the whole structure and makes functions more efficient.



Sample Programs

Create a structure for employee with following info: empid,name and salary. write a program to read the details of 'n' employees and display the details of employees whose salary is above 10000.Use pointer to structure. ( university question)

#include <stdio.h>
#include <stdlib.h>
struct Employee{
int eid;
char name[50];
float salary;
};
int main()
{
struct Employee *ptr;
int i, num;
printf("Enter number of persons: ");
scanf("%d", &num);
ptr = (struct Employee*) malloc(num * sizeof(struct Employee));
for(i = 0; i < num; ++i)
{
printf("Enter name, empid and salary:\n");
scanf("%s%d%f", (ptr+i)->name, &(ptr+i)->eid, &(ptr+i)->salary);
}
printf("Displaying Employees with salary above 10000:\n");
for(i = 0; i < num; ++i)
if((ptr+i)->salary >10000)
printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->eid, (ptr+i)->salary);
return 0;
}


Define a structure named Student with members roll_no, name, total_mark, percentage & grade. Create 10 student records, input roll_no, name & total_mark (out of 500) only. Write a C functions to evaluate and update percentage & grade of every student. Grades are calculated as follows.( University Question)
grade=’O’, if percentage >= 90,
grade=’A’, if percentage >= 80 and <90
grade=’B’, if percentage >= 70 and <80
grade=’C’, if percentage >= 60 and <70
grade=’D’, if percentage >= 50 and <60
grade=’E’, if percentage >= 40 and <50
grade=’F’, if percentage < 40
#include <stdio.h>
struct Student {
    int roll_no;
    char name[50];
    int total_mark;
    float percentage;
    char grade;
};

// Function to calculate percentage and grade
void calculateGrade(struct Student *s) {
    s->percentage = (s->total_mark / 500.0f) * 100;

    if (s->percentage >= 90)
        s->grade = 'O';
    else if (s->percentage >= 80)
        s->grade = 'A';
    else if (s->percentage >= 70)
        s->grade = 'B';
    else if (s->percentage >= 60)
        s->grade = 'C';
    else if (s->percentage >= 50)
        s->grade = 'D';
    else if (s->percentage >= 40)
        s->grade = 'E';
    else
        s->grade = 'F';
}

int main() {
    struct Student students[10];
    int i;

    // Input data for 10 students
    for (i = 0; i < 10; i++) {
        printf("\nEnter details of student %d\n", i + 1);
        printf("Roll No: ");
        scanf("%d", &students[i].roll_no);
        printf("Name: ");
        scanf(" %[^\n]", students[i].name);
        printf("Total Marks (out of 500): ");
        scanf("%d", &students[i].total_mark);

        // Calculate percentage and grade
        calculateGrade(&students[i]);
    }

    // Display student details
    printf("\n%-10s %-20s %-10s %-12s %-6s\n", "Roll No", "Name", "Marks", "Percentage", "Grade");
    printf("---------------------------------------------------------------\n");

    for (i = 0; i < 10; i++) {
        printf("%-10d %-20s %-10d %-12.2f %-6c\n",
               students[i].roll_no,
               students[i].name,
               students[i].total_mark,
               students[i].percentage,
               students[i].grade);
    }

    return 0;
}

Write a C function to display the details of all students with grade=’O’ in the above student records.
void displayOutstandingStudents(struct Student students[], int n) {
    int i, found = 0;

    printf("\nStudents with Grade 'O' (Outstanding):\n");
    printf("%-10s %-20s %-10s %-12s %-6s\n", "Roll No", "Name", "Marks", "Percentage", "Grade");
    printf("---------------------------------------------------------------\n");

    for (i = 0; i < n; i++) {
        if (students[i].grade == 'O') {
            printf("%-10d %-20s %-10d %-12.2f %-6c\n",
                   students[i].roll_no,
                   students[i].name,
                   students[i].total_mark,
                   students[i].percentage,
                   students[i].grade);
            found = 1;
        }
    }

    if (!found) {
        printf("No student with grade 'O' found.\n");
    }
}

Write a C program that uses a structure named Time with two members:
• hours (of type int)
• minutes (of type int)
Implement functions to add and subtract two-time values, ensuring that minutes are properly adjusted (for example, 90 minutes should be converted to 1 hour and 30 minutes).
• Use pointers to structures as function parameters.
• Display the final result in a readable hh:mm format.

#include <stdio.h>

/* Structure definition */
struct Time {
    int hours;
    int minutes;
};

/* Function to normalize time (adjust minutes) */
void normalizeTime(struct Time *t) {
    if (t->minutes >= 60) {
        t->hours += t->minutes / 60;
        t->minutes = t->minutes % 60;
    }
    else if (t->minutes < 0) {
        int borrow = (-t->minutes + 59) / 60;
        t->hours -= borrow;
        t->minutes += borrow * 60;
    }
}

/* Function to add two times */
struct Time addTime(struct Time *t1, struct Time *t2) {
    struct Time result;
    result.hours = t1->hours + t2->hours;
    result.minutes = t1->minutes + t2->minutes;

    normalizeTime(&result);
    return result;
}

/* Function to subtract two times */
struct Time subtractTime(struct Time *t1, struct Time *t2) {
    struct Time result;
    result.hours = t1->hours - t2->hours;
    result.minutes = t1->minutes - t2->minutes;

    normalizeTime(&result);
    return result;
}

/* Function to display time in hh:mm format */
void displayTime(struct Time *t) {
    printf("%02d:%02d\n", t->hours, t->minutes);
}

int main() {
    struct Time time1 = {2, 50};
    struct Time time2 = {1, 30};

    struct Time sum = addTime(&time1, &time2);
    struct Time diff = subtractTime(&time1, &time2);

    printf("Time 1: ");
    displayTime(&time1);

    printf("Time 2: ");
    displayTime(&time2);

    printf("Addition: ");
    displayTime(&sum);

    printf("Subtraction: ");
    displayTime(&diff);

    return 0;
}

Write a C program that defines a structure named CricketPlayer with the following members: name, team, matches_played, runs_scored The program should: 
1. Input details for 10 players. 
2. Use functions and structure pointers to find and display the player with the highest runs scored. 3. Finally, display the details of all the players.

#include <stdio.h>

/* Structure definition */
struct CricketPlayer {
    char name[50];
    char team[50];
    int matches_played;
    int runs_scored;
};

/* Function to find the player with highest runs */
struct CricketPlayer* findHighestRuns(struct CricketPlayer *players, int n) {
    int i;
    struct CricketPlayer *maxPlayer = &players[0];

    for (i = 1; i < n; i++) {
        if (players[i].runs_scored > maxPlayer->runs_scored) {
            maxPlayer = &players[i];
        }
    }
    return maxPlayer;
}

/* Function to display details of a player */
void displayPlayer(struct CricketPlayer *p) {
    printf("Name            : %s\n", p->name);
    printf("Team            : %s\n", p->team);
    printf("Matches Played  : %d\n", p->matches_played);
    printf("Runs Scored     : %d\n", p->runs_scored);
    printf("-------------------------------\n");
}

int main() {
    struct CricketPlayer players[10];
    int i;

    /* 1. Input details for 10 players */
    for (i = 0; i < 10; i++) {
        printf("\nEnter details for Player %d\n", i + 1);

        printf("Name: ");
        scanf(" %[^\n]", players[i].name);

        printf("Team: ");
        scanf(" %[^\n]", players[i].team);

        printf("Matches Played: ");
        scanf("%d", &players[i].matches_played);

        printf("Runs Scored: ");
        scanf("%d", &players[i].runs_scored);
    }

    /* 2. Find and display player with highest runs */
    struct CricketPlayer *topPlayer = findHighestRuns(players, 10);

    printf("\nPlayer with Highest Runs Scored:\n");
    displayPlayer(topPlayer);

    /* 3. Display details of all players */
    printf("\nDetails of All Players:\n");
    for (i = 0; i < 10; i++) {
        displayPlayer(&players[i]);
    }

    return 0;
}


Programs to try

1.Create a structure for employee with following info: empid, name and salary. Write a program to read the details of 'n' employees and display the details of employees whose salary is above 10000.Use pointer to structure. ( university question)

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays