Structures

Back

Loading concept...

πŸ—οΈ C Structures: Building Your Own Data Types

The Story Begins: Meet the Box Factory πŸ“¦

Imagine you have a magical box factory. Each box can hold many different things together β€” a toy car, a label with its name, and a price tag. Instead of carrying three separate items around, you put them all in ONE box.

That’s exactly what a Structure does in C! It lets you bundle different pieces of information into ONE custom package.


🌟 Structures Overview

What is a Structure?

A structure is like a recipe for a custom box. You decide what goes inside:

// This is like designing a box
struct Student {
    char name[50];
    int age;
    float grade;
};

Why do we need structures?

Think about a student. They have:

  • A name (text)
  • An age (number)
  • A grade (decimal number)

Without structures, you’d need THREE separate variables. With structures? Just ONE variable holds everything!

Real Life Example:

  • Your school ID card = a structure (has name, photo, class, roll number)
  • A contact in your phone = a structure (has name, phone number, email)

πŸ“‹ Structure Declaration

How to Create Your Custom Box Design

There are 3 ways to declare a structure:

Method 1: Declare first, use later

struct Book {
    char title[100];
    int pages;
    float price;
};

// Later, create a book:
struct Book myBook;

Method 2: Declare and create together

struct Car {
    char brand[30];
    int year;
} myCar, yourCar;

Method 3: Use typedef (give it a shorter name)

typedef struct {
    char name[50];
    int age;
} Person;

// Now just say:
Person friend1;

Think of it like this:

  • struct Book = Your box design blueprint
  • myBook = An actual box made from that blueprint

πŸ”‘ Structure Members and Access

Reaching Inside the Box

Each item inside a structure is called a member. To get or set a member, use the dot operator (.).

struct Pet {
    char name[30];
    int age;
    char type[20];
};

struct Pet dog;

// Put values IN the box:
strcpy(dog.name, "Buddy");
dog.age = 3;
strcpy(dog.type, "Golden Retriever");

// Take values OUT of the box:
printf("My pet is %s\n", dog.name);
printf("Age: %d years\n", dog.age);

The dot (.) is like opening the box and pointing to what you want!

graph TD A["dog"] --> B[".name = Buddy"] A --> C[".age = 3"] A --> D[".type = Golden Retriever"]

🎁 Structure Initialization

Filling Your Box Right Away

You can put items in your box at the moment you create it:

Method 1: In order (most common)

struct Point {
    int x;
    int y;
};

struct Point p1 = {10, 20};
// x = 10, y = 20

Method 2: By name (C99 and later)

struct Point p2 = {
    .y = 50,
    .x = 30
};
// Order doesn't matter when you use names!

Method 3: Partial initialization

struct Point p3 = {5};
// x = 5, y = 0 (unset = 0)

Pro tip: If you don’t initialize, members have garbage (random) values. Always initialize!


🎭 Nested Structures

Boxes Inside Boxes!

Sometimes you need a box that contains another box. That’s called nesting.

// First box: Date
struct Date {
    int day;
    int month;
    int year;
};

// Second box: Contains a Date box inside!
struct Employee {
    char name[50];
    int id;
    struct Date birthday;  // A box inside!
    struct Date joinDate;  // Another box inside!
};

How to access nested members? Use TWO dots!

struct Employee emp;

strcpy(emp.name, "Alice");
emp.id = 101;
emp.birthday.day = 15;
emp.birthday.month = 6;
emp.birthday.year = 1995;
graph TD E["Employee"] --> N[".name"] E --> I[".id"] E --> B[".birthday"] B --> BD[".day"] B --> BM[".month"] B --> BY[".year"]

πŸ“š Array of Structures

A Shelf Full of Boxes

What if you have 30 students? Create an array of structures!

struct Student {
    char name[50];
    int rollNo;
    float marks;
};

// Array of 30 student boxes:
struct Student class[30];

// Access first student:
strcpy(class[0].name, "Tom");
class[0].rollNo = 1;
class[0].marks = 85.5;

// Access fifth student:
class[4].rollNo = 5;

Think of it like:

  • class = A shelf
  • class[0] = First box on shelf
  • class[0].name = Name inside first box

Loop through all students:

for(int i = 0; i < 30; i++) {
    printf("Student: %s\n", class[i].name);
}

πŸš€ Structures and Functions

Passing Boxes Around

Structures can be sent to functions and returned from them!

Passing structure to function:

void printStudent(struct Student s) {
    printf("Name: %s\n", s.name);
    printf("Roll: %d\n", s.rollNo);
}

// Call it:
printStudent(class[0]);

Returning structure from function:

struct Point createPoint(int a, int b) {
    struct Point p;
    p.x = a;
    p.y = b;
    return p;
}

// Use it:
struct Point newPoint = createPoint(5, 10);

Passing by pointer (more efficient for big structures):

void updateAge(struct Student *s) {
    s->age = 20;  // Arrow -> for pointers!
}

// Call it:
updateAge(&class[0]);

Remember:

  • Use . with structure variables
  • Use -> with structure pointers

πŸ”— Self-Referential Structures

Boxes That Know About Other Boxes

A self-referential structure contains a pointer to itself. This is the magic behind linked lists, trees, and graphs!

struct Node {
    int data;
    struct Node *next;  // Points to another Node!
};

Why is this powerful?

You can create chains of boxes where each box points to the next:

struct Node first, second, third;

first.data = 10;
second.data = 20;
third.data = 30;

first.next = &second;   // First β†’ Second
second.next = &third;   // Second β†’ Third
third.next = NULL;      // Third β†’ Nothing (end)
graph LR A["first&lt;br&gt;data=10"] -->|next| B["second&lt;br&gt;data=20"] B -->|next| C["third&lt;br&gt;data=30"] C -->|next| D["NULL"]

Real world example:

  • A train! Each coach (structure) connects to the next coach.
  • A chain of paper clips!

Important: You can’t put a full structure inside itself (infinite size!), but you CAN put a pointer to another structure of the same type.


🎯 Quick Summary

Concept What It Does Example
Structure Bundle different data types struct Pet { ... }
Declaration Define the blueprint struct Book {...};
Members Items inside structure .name, .age
Initialization Fill values at creation = {10, 20}
Nested Structure inside structure emp.birthday.day
Array Many structures students[30]
Functions Pass/return structures printStudent(s)
Self-referential Points to same type struct Node *next

🌈 You Did It!

Congratulations! You now understand C Structures β€” your first step to creating powerful, organized programs. Structures are the foundation for:

  • Databases
  • Games (characters, items)
  • Operating systems
  • Almost every real program!

Remember: A structure is just a custom box that holds related things together. Simple as that! πŸ“¦βœ¨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.