Chapter 9: Structs and Unions

Introduction to Structs and Unions

Structs and unions are user-defined data types in C that allow you to group different types of variables under a single name. They are essential for creating complex data structures like linked lists, trees, and more. While both structs and unions group multiple variables, they differ in how they store and manage memory.

Structs

A struct (short for structure) is a collection of variables (can be of different types) grouped together under a single name. Each variable within a struct is called a member. Structs are useful for creating complex data types that represent real-world entities.

Declaring a Struct

To declare a struct, you use the struct keyword followed by the structure name and the list of members enclosed in curly braces {}:

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

Defining and Accessing Struct Variables

You can define a variable of the struct type by specifying the struct name followed by the variable name:

struct Person person1;

To access the members of the struct, you use the dot (.) operator:

person1.age = 30;
strcpy(person1.name, "John Doe");
person1.height = 5.9;

printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.1f\n", person1.height);

Initializing Struct Variables

You can initialize struct variables at the time of declaration:

struct Person person2 = {"Jane Doe", 28, 5.5};

Nested Structs

Structs can be nested within other structs, allowing you to create more complex data types:

struct Address {
char street[50];
char city[50];
int zip;
};

struct Person {
char name[50];
int age;
float height;
struct Address address;
};

struct Person person3 = {"Alice", 25, 5.4, {"123 Main St", "Wonderland", 12345}};

Pointers to Structs

You can create pointers to structs and use the arrow operator (->) to access members:

struct Person *ptr = &person3;
printf("Name: %s\n", ptr->name);
printf("City: %s\n", ptr->address.city);

Example: Creating a Linked List Node

Structs are commonly used to create linked lists. Here is an example of a linked list node:

struct Node {
int data;
struct Node *next;
};

Unions

A union is similar to a struct, but it only stores one of its members at a time. The size of a union is determined by the size of its largest member. Unions are useful for memory management when you need to store different types of data in the same memory location.

Declaring a Union

To declare a union, you use the union keyword followed by the union name and the list of members:

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

Defining and Accessing Union Variables

You can define a variable of the union type by specifying the union name followed by the variable name:

union Data data;

To access the members of the union, you use the dot (.) operator:

data.i = 10;
printf("data.i: %d\n", data.i);

data.f = 220.5;
printf("data.f: %.1f\n", data.f);

strcpy(data.str, "Hello");
printf("data.str: %s\n", data.str);

Example: Using a Union for Different Data Types

Here is an example of using a union to store different data types:

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

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

int main() {
union Data data;

data.i = 10;
printf("data.i: %d\n", data.i);

data.f = 220.5;
printf("data.f: %.1f\n", data.f);

strcpy(data.str, "Hello");
printf("data.str: %s\n", data.str);

return 0;
}

Structs vs. Unions

The key difference between structs and unions is how they manage memory:

  • Structs allocate memory for all their members, allowing you to store multiple values simultaneously.
  • Unions allocate memory for the largest member, allowing you to store only one value at a time, saving memory space when you need to handle multiple data types in the same location.

Practical Examples

Example 1: Defining a Struct for a Student Record

This example demonstrates defining a struct for a student record, initializing it, and accessing its members:

#include <stdio.h>

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

int main() {
struct Student student1 = {"John Doe", 101, 85.5};

printf("Name: %s\n", student1.name);
printf("Roll No: %d\n", student1.roll_no);
printf("Marks: %.2f\n", student1.marks);

return 0;
}

Example 2: Using a Union to Store Different Data Types

This example shows how to use a union to store different data types and print their values:

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

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

int main() {
union Data data;

data.i = 10;
printf("data.i: %d\n", data.i);

data.f = 220.5;
printf("data.f: %.1f\n", data.f);

strcpy(data.str, "Hello");
printf("data.str: %s\n", data.str);

return 0;
}

Example 3: Creating a Linked List

This example demonstrates using structs to create a simple linked list:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node *next;
};

void printList(struct Node *n) {
while (n != NULL) {
printf("%d -> ", n->data);
n = n->next;
}
printf("NULL\n");
}

int main() {
struct Node *head = NULL;
struct Node *second = NULL;
struct Node *third = NULL;

head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));

head->data = 1;
head->next = second;

second->data = 2;
second->next = third;

third->data = 3;
third->next = NULL;

printList(head);

return 0;
}

Conclusion

Structs and unions are powerful tools in C that allow you to create complex data types and manage memory efficiently. Structs enable you to group related variables and create sophisticated data structures, while unions allow you to save memory by storing only one value at a time. Understanding how to use structs and unions is crucial for effective C programming and for handling real-world data and memory management challenges.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *