Published on

Part 7: Structures and Unions in C

Authors

Welcome back to Part 7 of our "Getting Started with C" series! In the previous parts, we've worked with fundamental data types like integers, floats, and characters. Now, we're going to learn how to create our own user-defined data types using structures and unions. These powerful features allow you to group related data together in a meaningful way, making your code more organized and easier to manage.

Table of Contents

Structures in C

A structure in C is a composite data type that groups together variables of different data types under a single name. These variables are called members of the structure. Structures allow you to represent real-world entities that have multiple attributes.

Defining a Structure

To define a structure, you use the struct keyword followed by the structure name (also called the tag) and a block of member declarations enclosed in curly braces {}.

The syntax for defining a structure is:

struct structure_name {
    data_type member1_name;
    data_type member2_name;
    // ... more members
};

Example:

Let's define a structure to represent a point in 2D space:

struct Point {
    int x;
    int y;
};

Here, Point is the name of the structure, and it has two members: x and y, both of type int.

Declaring Structure Variables

Once you have defined a structure, you can declare variables of that structure type using the struct keyword followed by the structure name and the variable name.

Example:

struct Point p1; // Declares a structure variable named 'p1' of type 'struct Point'
struct Point p2; // Declares another structure variable named 'p2'

You can also declare and initialize structure variables at the same time:

struct Point p3 = {10, 20}; // Initializes p3 with x = 10 and y = 20

Accessing Structure Members

To access the individual members of a structure variable, you use the dot operator (.).

Example:

#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point p1;
    p1.x = 5;
    p1.y = 12;

    printf("Point p1: (%d, %d)\n", p1.x, p1.y); // Output: Point p1: (5, 12)

    struct Point p2 = {3, 7};
    printf("Point p2: (%d, %d)\n", p2.x, p2.y); // Output: Point p2: (3, 7)

    return 0;
}

Nested Structures

You can also have structures within other structures, which is known as nested structures.

Example:

Let's define a structure for a rectangle that uses our Point structure:

struct Rectangle {
    struct Point topLeft;
    struct Point bottomRight;
};

To access members of the inner structure, you use the dot operator multiple times:

struct Rectangle rect;
rect.topLeft.x = 0;
rect.topLeft.y = 10;
rect.bottomRight.x = 20;
rect.bottomRight.y = 0;

printf("Top-left corner: (%d, %d)\n", rect.topLeft.x, rect.topLeft.y);
printf("Bottom-right corner: (%d, %d)\n", rect.bottomRight.x, rect.bottomRight.y);

Pointers to Structures

You can also declare pointers to structure variables. The syntax is similar to declaring pointers to other data types:

struct Point *ptr_p; // Declares a pointer to a 'struct Point'

To access the members of a structure through a pointer, you use the arrow operator (->).

Example:

#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point p = {5, 12};
    struct Point *ptr_p = &p; // ptr_p now points to the memory location of p

    printf("Point p: (%d, %d)\n", p.x, p.y);
    printf("Point p via pointer: (%d, %d)\n", ptr_p->x, ptr_p->y); // Using the arrow operator

    ptr_p->x = 15; // Modifying the value of x through the pointer
    printf("Point p after modification: (%d, %d)\n", p.x, p.y);

    return 0;
}

The arrow operator ptr_p->x is equivalent to (*ptr_p).x, but it's more concise and commonly used when working with pointers to structures.

Unions in C

A union in C is also a user-defined data type that can hold members of different data types. However, unlike structures where each member has its own memory location, all members of a union share the same memory location. This means that only one member of a union can hold a value at any given time. The size of a union is determined by the size of its largest member.

Defining a Union

The syntax for defining a union is similar to that of a structure, but you use the union keyword instead of struct.

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

Here, Data is the name of the union. It can hold an integer i, a floating-point number f, or a character array str, but only one of these at a time.

Declaring Union Variables and Accessing Members

You declare union variables and access their members using the dot operator, just like with structures.

Example:

#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); // Output: Data.i: 10

    data.f = 3.14;
    printf("Data.f: %f\n", data.f); // Output: Data.f: 3.14 (The value of i is now overwritten)

    strcpy(data.str, "Hello");
    printf("Data.str: %s\n", data.str); // Output: Data.str: Hello (The values of i and f are now overwritten)

    printf("Data.i after str assignment: %d\n", data.i); // Output: Some garbage value
    printf("Data.f after str assignment: %f\n", data.f); // Output: Some garbage value

    return 0;
}

As you can see from the output, when you assign a value to one member of a union, the values of the other members are overwritten because they share the same memory location.

Key Differences Between Structures and Unions

FeatureStructureUnion
MemoryEach member has its own memory location.All members share the same memory location.
SizeSum of the sizes of all members (usually).Size of the largest member.
Simultaneous StorageCan store values for all members at once.Can store a value for only one member at a time.
PurposeGrouping related data of different types.Saving memory when only one of the members is needed at a time.

When to Use Structures vs. Unions

  • Use structures when you need to group together different pieces of information that logically belong together and you need to store and access all of them simultaneously (e.g., representing a person with a name, age, and address).
  • Use unions when you have a situation where a variable might hold different types of data at different times, but never all at the same time, and you want to save memory by using the same memory location for different purposes (e.g., a variable that can be either an integer or a floating-point number, but not both simultaneously).

Example: Using Structures

Let's create a structure to represent a student with a name, roll number, and marks:

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

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

int main() {
    struct Student student1;

    strcpy(student1.name, "John Doe");
    student1.rollNumber = 101;
    student1.marks = 85.5;

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

    return 0;
}

What's Next?

In the next part of our "Getting Started with C" series, we will explore file handling in C, learning how to read data from and write data to files, which is essential for creating programs that can persist data.


Suggestions:

  • To refresh your understanding of different data types, you can revisit our earlier discussion on "[Link to your blog post about Variables and Data Types in C]".
  • As we used pointers with structures, you might want to review our explanation of "[Link to your blog post about Pointers in C]".
  • Thinking about grouping data might lead you to consider how data is organized in memory. You can explore this further in "[Link to a potential future blog post about Memory Layout of Structures and Unions]".
  • In the next part, we'll be dealing with files. You might want to think about how programs interact with the operating system to access files.

This content provides a comprehensive introduction to structures and unions in C for beginners, explaining their definition, usage, key differences, and when to use each. Remember to replace the bracketed placeholders with actual links to your blog posts. Let me know if you have any other requests!