Sometimes you need to group related data together โ a student has a name, an age, and a grade. Instead of juggling separate variables, C lets you bundle them into a structure using struct.
Defining a Struct
A struct is a blueprint for a composite type. You define it once, then create variables that have all those fields together.
#include
#include
struct Student {
char name[50];
int age;
float grade;
};
int main() {
struct Student s1;
strcpy(s1.name, "Alice");
s1.age = 20;
s1.grade = 92.5;
printf("%s is %d years old with grade %.1f\n", s1.name, s1.age, s1.grade);
return 0;
}
Try it Yourself โ
The Arrow Operator (->)
When you have a pointer to a struct, use -> instead of . to access members. It's shorthand for dereferencing then dotting: (*ptr).member becomes ptr->member.
#include
struct Point {
int x;
int y;
};
int main() {
struct Point p1 = {3, 7};
struct Point *ptr = &p1;
printf("(%d, %d)\n", ptr->x, ptr->y);
ptr->x = 10;
ptr->y = 20;
printf("(%d, %d)\n", ptr->x, ptr->y);
return 0;
}
Try it Yourself โ
Nested Structures
You can put a struct inside another struct. Great for modeling real-world relationships, like an address inside a person.
#include
#include
struct Address {
char street[100];
char city[50];
};
struct Person {
char name[50];
struct Address addr;
};
int main() {
struct Person p;
strcpy(p.name, "Bob");
strcpy(p.addr.street, "123 Main St");
strcpy(p.addr.city, "Springfield");
printf("%s lives at %s, %s\n", p.name, p.addr.street, p.addr.city);
return 0;
}
Try it Yourself โ