Day 6: Structs in C: Organizing Data without Classes
Source: Dev.to
Introduction
In languages like Java or Python you use classes to bundle data together.
C doesn’t have classes; it has something rawer: structs.
A struct (structure) is how we create custom data types. Without structs, storing a student’s data would require separate variables:
char *name1;
int age1;
float gpa1;
With structs you can group these fields into a single Student type, which is the ancestor of the “object” concept in object‑oriented programming.
Example: Defining and Using a Struct
// Day 6: Grouping chaos into order
#include
#include
// Before: Messy variables scattered everywhere
// char *name1 = "Alice"; int age1 = 20;
// After: A custom data type
// We define a blueprint called "Student"
typedef struct {
char name[50];
int age;
float gpa;
} Student;
int main() {
// Treat the data as a single "object"
// Initialize it like an array
Student s1 = {"Alice", 20, 3.8};
// Access fields using the dot operator (.)
printf("Name: %s\n", s1.name);
printf("GPA: %.2f\n", s1.gpa);
return 0;
}
View the source code on GitHub: