Hey, everyone I recently created a small project in C using pointers and structures. The program is a simple Student Record System where the user can enter the number of students, along with their name, age, and marks. The data is then stored dynamically in memory using malloc
and displayed neatly on the screen.
This project helped me understand how powerful pointers are in C programming. Instead of fixing the size of an array, I learned how to allocate memory at runtime, which makes programs more flexible and efficient. I also used structures to group related data (like name, age, and marks) for each student, making the program more organized.
Code:
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[50];
int age;
float marks;
};
int main() {
int n, i;
struct Student* ptr;
printf("Enter number of students: ");
scanf_s("%d", &n);
ptr = (struct Student*)malloc(n * sizeof(struct Student));
if (ptr == NULL) {
printf("Memory not allocated!\n");
return 1;
}
for (i = 0; i < n; i++) {
printf("\nEnter details of student %d\n", i + 1);
printf("Name: ");
scanf_s("%s", ptr[i].name, (unsigned)_countof(ptr[i].name));
printf("Age: ");
scanf_s("%d", &ptr[i].age);
printf("Marks: ");
scanf_s("%f", &ptr[i].marks);
}
printf("\n--- Student Records ---\n");
for (i = 0; i < n; i++) {
printf("Student %d: %s, Age: %d, Marks: %.2f\n",
i + 1, ptr[i].name, ptr[i].age, ptr[i].marks);
}
free(ptr);
return 0;
}
Output:
No comments:
Post a Comment