Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


Structure with Pointer in C Program


Write a C program that uses structures with pointers to store and access student information.

  • Define a Student structure to store ID, name, and marks of a student.
  • Create a pointer to the structure and assign it the address of s1.
  • Access and display structure members using the pointer (ptr->member).
  • Modify the marks field using the pointer, reflecting changes in the original structure.
Example : pgm.c
#include <stdio.h>

struct Student {
    int id;
    char name[50];
    float marks;
};

int main() {
    struct Student s1 = {101, "Alice", 88.5};

    // Create pointer to structure
    struct Student *ptr = &s1;

    // Access members using pointer
    printf("--- Accessing Structure Using Pointer ---\n");
    printf("ID: %d\n", ptr->id);
    printf("Name: %s\n", ptr->name);
    printf("Marks: %.2f\n", ptr->marks);

    // Modify data using pointer
    ptr->marks = 95.0;

    printf("\n--- After Modifying Marks Using Pointer ---\n");
    printf("ID: %d\n", s1.id);
    printf("Name: %s\n", s1.name);
    printf("Marks: %.2f\n", s1.marks);

    return 0;
}

Output :

--- Accessing Structure Using Pointer ---
ID: 101
Name: Alex
Marks: 88.50

--- After Modifying Marks Using Pointer ---
ID: 101
Name: Alex
Marks: 95.00