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 likename
,age
, andmarks
into one unit calledStudent
. -
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.
No comments:
Post a Comment