18.9.25

Structs and Pointers





Structs and Pointers in C

Hey, everyone today I tried something new in C programming using structures with pointers and dynamic memory allocation. At first it looked confusing, but after working on it, I realized it’s actually super useful.

Code:

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

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

int main() {
    struct Student* ptr;

   
    ptr = (struct Student*)malloc(sizeof(struct Student));

    if (ptr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    
    printf("Enter name: ");
    scanf_s("%49s", ptr->name, (unsigned)_countof(ptr->name));
    

    printf("Enter age: ");
    scanf_s("%d", &ptr->age);

    printf("Enter marks: ");
    scanf_s("%f", &ptr->marks);

    
    printf("\n--- Student Details ---\n");
    printf("Name: %s\n", ptr->name);
    printf("Age: %d\n", ptr->age);
    printf("Marks: %.2f\n", ptr->marks);

    
    free(ptr);

    return 0;
}
Output:




What I Learned

  • struct lets me group related data like name, age, and marks into one unit called Student.

  • With pointers, I can directly access and modify this struct in memory using ptr->field.

  • malloc gives memory at runtime (on the heap). This is better than static memory because it can adjust as per need.

  • Finally, I used free(ptr) to release memory, so my program doesn’t waste RAM.

Instead of just declaring one student normally, I learned how to manage memory myself. This is like leveling up in C programming. In the future, I’ll be able to handle multiple students or even bigger data structures dynamically.


No comments:

Post a Comment

rating System

Loading...

Understanding Arrays in C

The Bookshelf Analogy & Book-Author Example Arrays are one of the most essential concepts in C programming. They let you store multiple ...