Structures (struct) and Nested Structs
While arrays hold items of the same type, structures allow you to bundle heterogeneous data types together into a single custom record.
What is it?
A `struct` is a user-defined composite data type in C that groups related variables of different types under a single name.
Why is it used?
Used to model real-world records like Student profiles, Course details, Coordinates, and Employee database entries.
Detailed Explanation
Structure Operations:
• Declaration: `struct Student { int id; char name[50]; float fee; };`.
• Member Access: Dot operator (`student.id`).
• Pointer to Struct: Arrow operator (`ptr->id`). When you have a pointer to a struct, `ptr->id` is shorthand for `(*ptr).id`.
• `typedef`: Creates a friendly type alias so you don't have to type `struct Student` every time.
Syntax Structure
Syntax Blueprint
typedef struct {
int id;
char name[50];
} Student;
Student s1;
s1.id = 101;
Code Example
C Code
#include <stdio.h>
#include <string.h>
// Defining a Course structure with typedef alias
typedef struct {
int course_id;
char name[50];
float price;
int duration_weeks;
} Course;
// Function accepting pointer to struct (avoids copying entire struct)
void print_course_card(const Course *c) {
printf("Course ID: #%d\n", c->course_id); // Arrow operator
printf("Title: %s\n", c->name);
printf("Price: ₹%.2f\n", c->price);
printf("Duration: %d Weeks\n", c->duration_weeks);
}
int main() {
// Initializing structure
Course python_course = {101, "KLiC Advanced Python", 2500.0f, 10};
printf("=== IGM Computers Course Record ===\n");
print_course_card(&python_course); // Pass by address
return 0;
}
Explanation of the Code
• `typedef struct { ... } Course;` defines `Course` as a first-class type.
• `print_course_card(const Course *c)` accepts a pointer, using `->` for member access.
• Passing pointers to structs prevents costly memory copying.
Expected Output
=== IGM Computers Course Record ===
Course ID: #101
Title: KLiC Advanced Python
Price: ₹2500.00
Duration: 10 Weeks
Real-World Application
Structures are the foundational building blocks of C-based operating systems, TCP/IP network packet headers, and database rows.
Common Mistakes to Avoid
• Forgetting the closing semicolon `;` after the structure definition closing brace `};`.
• Using `.` instead of `->` when accessing members through a pointer.
Quick Practice Challenge
Create a `Point` struct with `int x` and `int y` members, initialize it to `{10, 20}`, and print both values.
Key Takeaways
• Structures group variables of different data types into one entity.
• Use dot `.` on instances and arrow `->` on pointers to structs.
• Use `typedef` to create clean type aliases.