Structures (struct)
struct Student {
char name[50];
int age;
float gpa;
};
int main() {
struct Student s1 = {"Riya", 20, 3.8};
printf("%s is %d years old, GPA %.1f\n", s1.name, s1.age, s1.gpa);
return 0;
}
The dot operator . accesses a specific field inside a structure variable. This groups related data logically — much cleaner than having three separate, unrelated variables floating around your program.
Writing struct Student every time you declare a new variable gets repetitive. typedef lets you create a shorter alias:
typedef struct {
char name[50];
int age;
} Student;
int main() {
Student s1 = {"Aman", 22}; // no 'struct' keyword needed anymore
return 0;
}
typedef struct {
char name[30];
int score;
} Player;
int main() {
Player team[3] = {
{"Vikram", 85},
{"Sana", 92},
{"Dev", 78}
};
for (int i = 0; i < 3; i++) {
printf("%s: %d\n", team[i].name, team[i].score);
}
return 0;
}
This pattern — an array of structures — is how you'd model something like a leaderboard, a student roster, or an inventory of products, each with the same fields but different values.
When working with a pointer to a structure, use the arrow operator -> instead of the dot, which automatically dereferences and accesses the field in one step:
Student s1 = {"Neha", 21, 3.9};
Student *ptr = &s1;
printf("%s\n", ptr->name); // shorthand for (*ptr).name
Use the dot . operator on a regular structure variable, and the arrow -> operator on a pointer to a structure. Mixing them up — writing ptr.name instead of ptr->name — causes a compiler error, and is one of the most frequent small mistakes when first combining structures with pointers.
Define a Book structure with title, author, and year fields, create two Book variables, and print both of their details.
#include <stdio.h>
typedef struct {
char title[50];
char author[30];
int year;
} Book;
int main() {
Book b1 = {"1984", "George Orwell", 1949};
Book b2 = {"Dune", "Frank Herbert", 1965};
printf("%s by %s (%d)\n", b1.title, b1.author, b1.year);
printf("%s by %s (%d)\n", b2.title, b2.author, b2.year);
return 0;
}