C Structures and Unions

Create custom data types using structures and unions for complex data organization.

What are Structures?

A structure is a user-defined data type that allows you to group different data types together under a single name.

Key features:
- Structures group related data together
- Each member can be of different data type
- Members are accessed using the dot operator (.)
- Structures help organize complex data
- They make code more readable and maintainable

Basic syntax:
```c
struct structure_name {
    data_type member1;
    data_type member2;
    // ... more members
};
```

Structure Declaration and Definition

Structure Declaration:
```c
struct Student {
    int roll_number;
    char name[50];
    float marks;
};
```

Creating structure variables:
```c
// Method 1: Declare structure, then create variables
struct Student s1, s2;

// Method 2: Create variables during declaration
struct Student {
    int roll_number;
    char name[50];
    float marks;
} s1, s2;

// Method 3: Using typedef
typedef struct {
    int roll_number;
    char name[50];
    float marks;
} Student;
Student s1, s2;  // No need for 'struct' keyword
```

Accessing Structure Members

Structure members are accessed using the dot operator (.):

Syntax: `structure_variable.member_name`

Example:
```c
struct Student {
    int roll_number;
    char name[50];
    float marks;
};

struct Student s1;

// Assigning values
s1.roll_number = 101;
strcpy(s1.name, "John Doe");
s1.marks = 85.5;

// Accessing values
printf("Roll Number: %d\n", s1.roll_number);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n", s1.marks);
```

Structure Initialization

Structures can be initialized in several ways:

1. Declaration with initialization:
```c
struct Student s1 = {101, "John Doe", 85.5};
```

2. Designated initialization (C99):
```c
struct Student s1 = {
    .name = "John Doe",
    .roll_number = 101,
    .marks = 85.5
};
```

3. Partial initialization:
```c
struct Student s1 = {101};  // Only first member initialized
```

4. Zero initialization:
```c
struct Student s1 = {0};  // All members initialized to 0
```

Unions

A union is similar to a structure, but all members share the same memory location.

Key differences from structures:
- Only one member can be used at a time
- All members share the same memory space
- Size of union = size of largest member
- Useful for memory optimization

Union syntax:
```c
union Data {
    int integer;
    float floating;
    char character;
};

union Data data;
data.integer = 10;      // Now integer is active
data.floating = 3.14;   // Now floating is active (integer is overwritten)
```

Practice Examples

Try these examples in our online C compiler to reinforce your learning:

Basic Structure Example

Demonstrates basic structure declaration, input, and output.

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

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

int main() {
    struct Student s1;
    
    // Input student details
    printf("Enter roll number: ");
    scanf("%d", &s1.roll_number);
    
    printf("Enter name: ");
    scanf("%s", s1.name);
    
    printf("Enter marks: ");
    scanf("%f", &s1.marks);
    
    // Display student details
    printf("\nStudent Details:\n");
    printf("Roll Number: %d\n", s1.roll_number);
    printf("Name: %s\n", s1.name);
    printf("Marks: %.2f\n", s1.marks);
    
    return 0;
}

Array of Structures

Shows how to work with arrays of structures.

#include <stdio.h>

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

int main() {
    struct Book library[3];
    
    // Input book details
    for (int i = 0; i < 3; i++) {
        printf("\nBook %d:\n", i + 1);
        printf("Enter title: ");
        scanf("%s", library[i].title);
        printf("Enter author: ");
        scanf("%s", library[i].author);
        printf("Enter pages: ");
        scanf("%d", &library[i].pages);
        printf("Enter price: ");
        scanf("%f", &library[i].price);
    }
    
    // Display all books
    printf("\nLibrary Catalog:\n");
    for (int i = 0; i < 3; i++) {
        printf("\nBook %d:\n", i + 1);
        printf("Title: %s\n", library[i].title);
        printf("Author: %s\n", library[i].author);
        printf("Pages: %d\n", library[i].pages);
        printf("Price: $%.2f\n", library[i].price);
    }
    
    return 0;
}

Union Example

Demonstrates union usage and memory sharing.

#include <stdio.h>

union Data {
    int integer;
    float floating;
    char character;
};

int main() {
    union Data data;
    
    // Using as integer
    data.integer = 42;
    printf("Integer value: %d\n", data.integer);
    
    // Using as float (overwrites integer)
    data.floating = 3.14;
    printf("Float value: %.2f\n", data.floating);
    
    // Using as character (overwrites float)
    data.character = 'A';
    printf("Character value: %c\n", data.character);
    
    printf("\nSize of union: %zu bytes\n", sizeof(union Data));
    
    return 0;
}

Ready for the Next Step?

Continue your C programming journey with our next tutorial.

Next: C File Handling →