Paramclasses Academy - Blog

Tutorials Details

←
Post 14 of 15
→

What is Structures and Unions in C Programming

What is Structures and Unions in C Programming

October 14, 2026

1. Introduction

In C programming, structures and unions are user-defined data types that allow programmers to group multiple data members under a single name.

For example, a student record may contain:

  • Student ID (int)

  • Name (char array)

  • Age (int)

  • Marks (float)

Using separate variables for every student's information can become difficult to manage. Structures allow these related values to be grouped into one record.

Unions also group multiple members, but their memory behavior is different: their members share the same storage.

In this module, you will learn:

  • What structures and unions are

  • Why they are used

  • Structure declaration and initialization

  • Accessing structure members with the . operator

  • Using pointers to structures with ->

  • Arrays of structures

  • Nested structures

  • Passing structures to functions

  • Differences between structures and unions

  • Practical programs and interview questions

2. What Is a Structure in C?

A structure is a user-defined type that groups variables of potentially different data types into a single unit.

Syntax

struct structure_name
{
    data_type member1;
    data_type member2;
    data_type member3;
};

Example:

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

Here, Student is the structure tag, and id, name, and marks are its members.

This declaration defines the structure type. It does not, by itself, create a student object.

3. Why Do We Use Structures?

Structures are useful when several related values belong to one entity.

Common applications include:

  • Student records

  • Employee details

  • Product inventories

  • Bank account records

  • Customer information

  • Data exchanged between different parts of a program

For example, instead of managing studentId, studentName, and studentMarks as unrelated variables, you can group them inside a struct Student object.

4. Declaring Structure Variables

After defining a structure type, you can declare variables of that type.

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

int main(void)
{
    struct Student s1;
    struct Student s2;

    return 0;
}

Here, s1 and s2 are two separate structure objects. Each object has its own id, name, and marks members.

You can also declare structure variables immediately after the closing brace of a structure definition, although defining the type separately often improves readability.

5. Initializing a Structure

You can initialize structure members when declaring a structure variable.

#include <stdio.h>

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

int main(void)
{
    struct Student s1 = {101, "Rahul", 88.5f};

    printf("ID: %d\n", s1.id);
    printf("Name: %s\n", s1.name);
    printf("Marks: %.2f\n", s1.marks);

    return 0;
}

Output:

ID: 101
Name: Rahul
Marks: 88.50

The initializer values correspond to the members in declaration order.

Designated initializers

C also supports designated initializers, which identify members by name.

struct Student s1 = {
    .name = "Rahul",
    .marks = 88.5f,
    .id = 101
};

This can make initialization easier to read because the member order does not have to match the declaration order.

6. Accessing Structure Members

Use the dot operator (.) to access a member of a structure object.

Syntax

structure_variable.member_name

Example:

#include <stdio.h>

struct Employee
{
    int id;
    float salary;
};

int main(void)
{
    struct Employee e1;

    e1.id = 1001;
    e1.salary = 45000.0f;

    printf("Employee ID: %d\n", e1.id);
    printf("Salary: %.2f\n", e1.salary);

    return 0;
}

Output:

Employee ID: 1001
Salary: 45000.00

The statements e1.id = 1001; and e1.salary = 45000.0f; assign values to the corresponding members.

7. Taking User Input for a Structure

You can use standard input functions to populate structure members.

#include <stdio.h>

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

int main(void)
{
    struct Student s1;

    printf("Enter student ID: ");
    if (scanf("%d", &s1.id) != 1)
    {
        printf("Invalid ID.\n");
        return 1;
    }

    printf("Enter student name: ");
    if (scanf("%49s", s1.name) != 1)
    {
        printf("Invalid name.\n");
        return 1;
    }

    printf("Enter marks: ");
    if (scanf("%f", &s1.marks) != 1)
    {
        printf("Invalid marks.\n");
        return 1;
    }

    printf("\n--- Student Details ---\n");
    printf("ID: %d\n", s1.id);
    printf("Name: %s\n", s1.name);
    printf("Marks: %.2f\n", s1.marks);

    return 0;
}

Example output:

Enter student ID: 101
Enter student name: Rahul
Enter marks: 91.5

--- Student Details ---
ID: 101
Name: Rahul
Marks: 91.50

This example uses %49s to prevent writing more than 49 characters into the 50-character name array. It reads only one word for the name; use fgets() when you need to accept spaces.

8. Array of Structures

An array of structures stores multiple records of the same structure type.

Example:

#include <stdio.h>

struct Student
{
    int id;
    char name[30];
    float marks;
};

int main(void)
{
    struct Student students[3] = {
        {101, "Aman", 85.0f},
        {102, "Priya", 92.0f},
        {103, "Ravi", 78.5f}
    };

    for (int i = 0; i < 3; i++)
    {
        printf("ID: %d, Name: %s, Marks: %.2f\n",
               students[i].id,
               students[i].name,
               students[i].marks);
    }

    return 0;
}

Output:

ID: 101, Name: Aman, Marks: 85.00
ID: 102, Name: Priya, Marks: 92.00
ID: 103, Name: Ravi, Marks: 78.50

The array students contains three records. The expression students[i].name accesses the name member of the record at index i.

9. Pointers to Structures

A pointer can store the address of a structure object.

Syntax

struct Student *ptr;

When accessing a member through a structure pointer, use the arrow operator (->).

Example:

#include <stdio.h>

struct Student
{
    int id;
    float marks;
};

int main(void)
{
    struct Student s1 = {101, 89.5f};
    struct Student *ptr = &s1;

    printf("ID: %d\n", ptr->id);
    printf("Marks: %.2f\n", ptr->marks);

    return 0;
}

Output:

ID: 101
Marks: 89.50

The expression ptr->id is equivalent to (*ptr).id.

Remember to initialize the pointer to a valid structure object before dereferencing it.

10. Nested Structures

A nested structure is a structure that contains another structure as one of its members.

Example:

#include <stdio.h>

struct Date
{
    int day;
    int month;
    int year;
};

struct Employee
{
    int id;
    char name[30];
    struct Date joiningDate;
};

int main(void)
{
    struct Employee e1 = {
        1001,
        "Aman",
        {15, 6, 2024}
    };

    printf("Employee: %s\n", e1.name);
    printf("Joining Date: %02d-%02d-%04d\n",
           e1.joiningDate.day,
           e1.joiningDate.month,
           e1.joiningDate.year);

    return 0;
}

Output:

Employee: Aman
Joining Date: 15-06-2024

The nested member is accessed using chained dot operators, such as e1.joiningDate.year.

11. Passing Structures to Functions

Structures can be passed to functions by value or through pointers.

Passing a structure by value

#include <stdio.h>

struct Rectangle
{
    float length;
    float width;
};

float calculateArea(struct Rectangle r)
{
    return r.length * r.width;
}

int main(void)
{
    struct Rectangle rect = {10.0f, 5.0f};

    printf("Area: %.2f\n", calculateArea(rect));

    return 0;
}

Output:

Area: 50.00

The function receives a copy of the structure. Changes to that copy do not change the original structure object.

Passing a pointer to a structure

For larger structures, passing a pointer can avoid copying the entire structure. It also allows a function to modify the original object when needed.

void updateMarks(struct Student *s, float newMarks)
{
    s->marks = newMarks;
}

The caller must pass the address of a valid struct Student object.

12. What Is a Union in C?

A union is a user-defined type whose members share the same memory storage.

Syntax

union Data
{
    int number;
    float decimal;
    char character;
};

You can declare a union variable as follows:

union Data value;

Unlike a structure, a union is generally intended to hold one active member value at a time. Writing to one member changes the shared storage and can affect the interpretation of other members.

Example:

#include <stdio.h>

union Data
{
    int number;
    float decimal;
    char character;
};

int main(void)
{
    union Data value;

    value.number = 100;
    printf("Number: %d\n", value.number);

    value.decimal = 25.5f;
    printf("Decimal: %.2f\n", value.decimal);

    return 0;
}

Output:

Number: 100
Decimal: 25.50

After assigning to value.decimal, the previous value.number value is no longer the active member value to read. For portable programs, read the member whose value was most recently stored, subject to the language's union rules.

13. Difference Between Structure and Union

Feature

Structure (struct)

Union (union)

Memory

Each member has its own storage within the object

Members share storage

Member values

Multiple members can hold their values simultaneously

Typically one member value is active at a time

Size

At least enough for all members, including padding

At least enough for its largest member, including alignment requirements

Use case

Records containing related fields

Storage shared among alternative representations

Member access

Uses . or ->

Uses . or ->

Example use cases:

  • Use a structure for a student record containing ID, name, and marks.

  • Consider a union when a value may represent one of several alternative data types and memory efficiency is important.

14. Real-World Example: Product Inventory

This program stores and displays information about products.

#include <stdio.h>

struct Product
{
    int id;
    char name[40];
    float price;
    int quantity;
};

int main(void)
{
    struct Product p = {501, "Keyboard", 799.0f, 10};

    printf("--- Product Details ---\n");
    printf("Product ID: %d\n", p.id);
    printf("Product Name: %s\n", p.name);
    printf("Price: %.2f\n", p.price);
    printf("Quantity: %d\n", p.quantity);
    printf("Stock Value: %.2f\n", p.price * p.quantity);

    return 0;
}

Output:

--- Product Details ---
Product ID: 501
Product Name: Keyboard
Price: 799.00
Quantity: 10
Stock Value: 7990.00

This is a simple example of how structures can represent real-world entities in inventory, billing, and record-management systems.

15. Common Mistakes

Mistake 1: Forgetting the semicolon after a structure definition

Incorrect:

struct Student
{
    int id;
}

Correct:

struct Student
{
    int id;
};

Mistake 2: Using the wrong member-access operator

  • Use . with a structure object.

  • Use -> with a pointer to a structure.

Mistake 3: Assuming all union members retain independent values

Union members share storage, so assigning one member can change the representation of the others.

Mistake 4: Forgetting to initialize members

Uninitialized automatic structure members may have indeterminate values. Initialize members before reading them.

Mistake 5: Using unsafe string input

When reading a string into a fixed-size character array, ensure the input operation cannot exceed the buffer's capacity.

16. Practical Programs for Practice

  1. Create a structure to store student details.

  2. Input and display employee information.

  3. Store five students using an array of structures.

  4. Find the student with the highest marks.

  5. Create a nested structure for a person's date of birth.

  6. Pass a structure to a function and calculate an area.

  7. Use a structure pointer to update employee salary.

  8. Create a union with integer, float, and character members.

  9. Compare the behavior of a structure and a union.

  10. Build a simple product inventory program.

17. Interview Questions

Q1. What is a structure in C?

A user-defined type that groups related members, potentially of different data types, into one object.

Q2. What is a union?

A user-defined type in which all members share the same storage.

Q3. What is the difference between . and ->?

The dot operator accesses a member through a structure object; the arrow operator accesses a member through a pointer to a structure.

Q4. Can a structure contain another structure?

Yes. This is called a nested structure.

Q5. Can an array contain structures?

Yes. An array of structures stores multiple objects of the same structure type.

Q6. Can a structure be passed to a function?

Yes. It can be passed by value or through a pointer.

Q7. Why use a union?

A union allows different alternative members to share storage.

Q8. Does a structure's size always equal the sum of its member sizes?

No. The compiler may add padding for alignment.

18. Quick Revision

  • Structures group related data members.

  • Unions share storage among their members.

  • Use struct and union to declare these types.

  • Use . to access members through an object.

  • Use -> to access members through a pointer.

  • Arrays of structures store multiple records.

  • Nested structures model complex records.

  • Functions can receive structures by value or pointer.

  • Structure and union sizes can include padding.

  • Initialize members and validate input before using stored values.

19. Homework

  1. Define a structure and explain its advantages.

  2. Explain the difference between structures and unions.

  3. Write a program to store and display student details.

  4. Create an array of structures for five employees.

  5. Write a program using a pointer to a structure.

  6. Explain nested structures with an example.

  7. Write a program to find the product with the highest price.

  8. Explain why structure size may differ from the sum of its member sizes.

Conclusion

In this module, you learned how to create and use structures and unions, access their members, work with structure pointers and arrays, nest structures, and pass structures to functions.

←
Post 14 of 15
→