C Programming - Beginner to Brilliance / Structures and Unions

Defining and Using Structures

๐Ÿง  What is a Structure?

A structure in C allows you to group variables of different types under one single name. It is a way to create your own custom data type.

๐Ÿ“ฆ A structure is like a box that can hold different types of data โ€” like a name (string), age (int), and salary (float) โ€” all in one unit.


๐Ÿ› ๏ธ Why Use Structures?

C provides primitive data types like int, float, char, etc. But real-world data is usually more complex.

๐Ÿ’ก Example:

Suppose you want to store student data like:

  • Roll Number (int)

  • Name (string)

  • Percentage (float)

You can either use three separate variables:

int roll;
char name[50];
float percentage;

But if you want to manage 100 students, it becomes messy.

๐Ÿ”น struct Keyword

The struct keyword in C is used to define a structure, which is a user-defined data type that allows grouping of variables of different types under a single name.

Why Use struct?

Purpose

Explanation

Group related data

Combine different types (int, char[], float) together

Real-world mapping

Represent real-world entities like Student, Book, Employee

Pass as a single unit

Pass a full record to functions easily

Organize code

Make large programs more readable and maintainable

โœ… Instead, define a structure:

struct Student {
    int roll;
    char name[50];
    float percentage;
};

Now you can create multiple student objects, each containing all these fields grouped together.


๐Ÿงฉ Step-by-Step: Defining a Structure

๐Ÿ”ค Syntax:

struct StructureName {
    dataType member1;
    dataType member2;
    ...
};

โœ… Example:

struct Student {
    int roll;
    char name[50];
    float percentage;
};

๐Ÿงพ This does not create any variables yet, just a template or blueprint.


๐Ÿ‘ค Declaring Structure Variables

After defining the structure, you can create variables like this:

struct Student s1, s2;

Now s1 and s2 each have their own roll, name, and percentage.


๐Ÿงช Accessing Members (Dot Operator)

Use the dot operator (.) to access structure members.

s1.roll = 101;
strcpy(s1.name, "Rahul");
s1.percentage = 92.5;

Note: Use strcpy() to copy string data into character arrays.

Print values:

printf("Roll: %d\\n", s1.roll);
printf("Name: %s\\n", s1.name);
printf("Percentage: %.2f\\n", s1.percentage);

๐Ÿ’ก Shortcut with typedef

Typing struct Student every time is long. So we can shorten it using typedef.

typedef struct Student {
    int roll;
    char name[50];
    float percentage;
} Student;

Now you can declare:

Student s1, s2;

Much cleaner and easier!


๐Ÿ“‹ Multiple Structure Variables

You can declare structure variables at the time of definition:

#include <stdio.h>
																			// Structure definition with variable declarations
struct Book {
    int id;
    char title[100];
    float price;
} book1 = {101, "C Programming", 299.99},
  book2 = {102, "Data Structures", 399.50};  // Initialized at declaration

int main() {
																					    // Printing details of book1
    printf("Book 1:\\n");
    printf("ID: %d\\n", book1.id);
    printf("Title: %s\\n", book1.title);
    printf("Price: %.2f\\n\\n", book1.price);

																						  // Printing details of book2
    printf("Book 2:\\n");
    printf("ID: %d\\n", book2.id);
    printf("Title: %s\\n", book2.title);
    printf("Price: %.2f\\n", book2.price);

    return 0;
}

โœ… Method 1: Designated Initializers (C99+)

struct Student s1 = { .roll = 1, .name = "Amit", .percentage = 85.0 };

โœ… Method 2: Positional Initialization

struct Student s1 = { 1, "Amit", 85.0 };

Works only if the order matches the structure definition.


๐Ÿ”ข Array of Structures

To store multiple records:


๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘ Structures with Functions

๐Ÿ”น Passing by Value

#include <stdio.h>

// Define the structure
struct Student {
    int roll;
    char name[50];
    float percentage;
};

// Function that accepts structure by value
void printStudent(struct Student s) {
    printf("Student Details:\\n");
    printf("Roll: %d\\n", s.roll);
    printf("Name: %s\\n", s.name);
    printf("Percentage: %.2f\\n", s.percentage);
}

int main() {
    // Declare and initialize a structure variable
    struct Student s1 = {101, "Rahul", 92.5};

    // Function call (passing structure by value)
    printStudent(s1);

    return 0;
}
Student Details:
Roll: 101
Name: Rahul
Percentage: 92.50โš ๏ธ Value is copied. Any changes inside the function won't affect the original.

๐Ÿ”น Passing by Reference (Pointer)

#include <stdio.h>

// Define the structure
struct Student {
    int roll;
    char name[50];
    float percentage;
};

// Function that modifies structure using pointer (pass by reference)
void update(struct Student *s) {
    s->percentage += 5;  // Increase percentage by 5
}

int main() {
    // Declare and initialize structure variable
    struct Student s1 = {101, "Rahul", 85.0};

    // Print before update
    printf("Before update:\\n");
    printf("Roll: %d\\n", s1.roll);
    printf("Name: %s\\n", s1.name);
    printf("Percentage: %.2f\\n", s1.percentage);

    // Function call (passing structure by reference)
    update(&s1);

    // Print after update
    printf("\\nAfter update:\\n");
    printf("Roll: %d\\n", s1.roll);
    printf("Name: %s\\n", s1.name);
    printf("Percentage: %.2f\\n", s1.percentage);

    return 0;
}
Before update:
Roll: 101
Name: Rahul
Percentage: 85.00

After update:
Roll: 101
Name: Rahul
Percentage: 90.00

Use -> operator to access members via pointers.