C

Structures and Unions in C Programming

In C, basic data types (like int, char, and float) allow you to store single values. Arrays allow you to store multiple values of the same type. However, real-world data is often a collection of different types. For example, a "Student" has a Name (string), an Age (int), and a GPA (float).

To handle this, C provides User-Defined Data Types: Structures and Unions.

1. Structures (struct)

A Structure is a composite data type that allows you to group variables of different types under a single name. Each variable inside a structure is called a member.

The Theory: Memory Allocation

When you define a structure, the compiler allocates a contiguous block of memory large enough to hold all its members simultaneously. The total size of a structure is at least the sum of the sizes of its members (sometimes slightly more due to "memory padding" for CPU efficiency).

Syntax and Access

  • Defining: You use the struct keyword followed by the structure name and its members.

  • Accessing: You use the Dot operator (.) for structure variables and the Arrow operator (->) for pointers to structures.

2. Unions (union)

A Union is a special data type that allows you to store different data types in the same memory location.

The Theory: Shared Memory

Unlike a structure, a union allocates only enough memory to hold its largest member. All members share the exact same starting address. This means you can only store a value in one member at a time. If you write to a second member, the first one is overwritten.

Why use Unions?

Unions are primarily used for Memory Conservation in embedded systems or when creating hardware-level abstractions (like representing a register that can be accessed as a whole or as individual bytes).

3. Comparison: Structure vs. Union

FeatureStructure (struct)Union (union)
Keywordstructunion
MemoryEach member gets its own unique address.All members share the same address.
SizeSum of all members (plus padding).Size of the largest member.
AccessCan access all members at any time.Can only access one member at a time.
Use CaseGrouping related data (e.g., User Profile).Saving memory (e.g., Variant types).

4. Practical Code Example

This program demonstrates the definition, initialization, and size differences between a structure and a union.


#include <stdio.h>
#include <string.h>

// Defining a structure
struct Student {
    int id;
    char name[20];
    float gpa;
};

// Defining a union
union Data {
    int i;
    float f;
    char str[20];
};

int main() {
    // --- Structure Usage ---
    struct Student s1 = {101, "Alice", 3.8};
    printf("Structure - Student ID: %d, Name: %s, GPA: %.1f\n", s1.id, s1.name, s1.gpa);
    printf("Total Size of Struct: %zu bytes\n\n", sizeof(struct Student));

    // --- Union Usage ---
    union Data d1;
    
    d1.i = 10;
    printf("Union - d1.i: %d\n", d1.i);
    
    d1.f = 220.5; // This overwrites the memory used by 'i'
    printf("Union - d1.f: %.1f\n", d1.f);
    
    strcpy(d1.str, "C Programming"); // This overwrites 'f'
    printf("Union - d1.str: %s\n", d1.str);
    
    printf("Total Size of Union: %zu bytes\n", sizeof(union Data));

    return 0;
}

5. Advanced Concepts

A. Nested Structures

You can place one structure inside another. For example, a Student structure might contain a Date structure for the dateOfBirth.


struct Date { int d, m, y; };
struct Student {
    char name[20];
    struct Date dob; // Nested Structure
};

B. Typedef with Structures

The typedef keyword allows you to create an "alias" for a structure, so you don't have to type struct every time you declare a variable.

  • Example: typedef struct Student Student; allows you to simply write Student s1;.

C. Memory Padding (Theory)

You might notice sizeof(struct) is sometimes larger than the sum of its parts. For example, a struct with a char (1 byte) and an int (4 bytes) might take 8 bytes. The compiler adds "padding" bytes to ensure that the int starts on a memory address that is a multiple of 4, which helps the CPU fetch data faster.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now