Pointer to Structure

In C, a pointer to a structure is a pointer that points to a structure variable. This allows us to access and manipulate the structure’s members using the pointer. Using pointers with structures is efficient, especially for large structures, because it avoids copying the entire structure when passing it to functions.

Creating and Using Pointers to Structures

  1. Define a Structure: First, define the structure type.
  2. Declare a Structure Variable: Create an instance of the structure.
  3. Create a Pointer to the Structure: Declare a pointer that holds the address of the structure.
  4. Access Members: Use the -> (arrow) operator to access structure members through the pointer.

Structures can be created and accessed using pointers. A pointer variable of a structure can be created as below:

struct name {
member1;
member2;
.....
};
int main()
{
struct name *ptr;
}
Here, the pointer variable ptr of type struct name is created.

Accessing structure's member through pointer
A structure's member can be accessed through pointer in two ways:
1.Referencing pointer to another address to access memory.
2.Using dynamic memory allocation.

1. Referencing pointer to another address to access the memory
Consider an example to access structure's member through pointer.
#include <stdio.h>
typedef struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1;
// Referencing pointer to memory address of person1
printf("Enter Age: ");
scanf(“%d”,&personPtr->age); or scanf("%d",&(*personPtr).age);
printf("Enter Weight: ");
scanf("%f",&personPtr->weight);
printf("Displaying: ");
printf("%d%f",personPtr->age,personPtr->weight);
//can also use (*personPtr).age
return 0;
}

2. Accessing structure member through pointer using dynamic memory allocation
To access structure member using pointers, memory can be allocated dynamically using malloc() function defined under "stdlib.h" header file.
Syntax to use malloc()
ptr = (cast-type*) malloc(byte-size)
Example 
 structure's member access through pointer using malloc() function.
#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);
ptr = (struct person*) malloc(num * sizeof(struct person));
/* Above statement allocates the memory for n structures with pointer ptr pointing to base address */
for(i = 0; i < num; ++i)
{
printf("Enter name, age and weight of the person respectively:\n");
scanf("%s%d%f", (ptr+i)->name, &(ptr+i)->age, &(ptr+i)->weight);
}
printf("Displaying Infromation:\n");
for(i = 0; i < num; ++i)
printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)->weight);
return 0;
}

Why Use Pointers to Structures?

  • Memory Efficiency: Passing pointers avoids copying large structures.
  • Dynamic Access: Useful when working with arrays of structures or structures created dynamically with malloc.
  • Flexible Parameter Passing: Structure pointers are commonly passed to functions to avoid passing large data.
Passing a Pointer to Structure to a Function
#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;
}


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");
    }
}



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