C Structures and unions


Structures and unions in C are user-defined data types that allow you to store multiple variables of different data types together. Both are used to group related data, but they differ in how they store and access memory.

Structures in C

A structure is a user-defined data type that groups variables of different data types under a single name. Each member of the structure occupies its own space in memory, making structures useful for grouping logically related data.

Defining a Structure

To define a structure, you use the struct keyword:

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

Here:

  • Person is a structure containing three fields: name, age, and height.
  • Each member of the structure can have a different data type.

Declaring and Using Structures

You can declare variables of a structure type like this:

struct Person person1; strcpy(person1.name, "Alice"); person1.age = 25; person1.height = 5.7; printf("Name: %s\n", person1.name); printf("Age: %d\n", person1.age); printf("Height: %.1f\n", person1.height);

You can also initialize a structure at the time of declaration:

struct Person person2 = {"Bob", 30, 6.0};

Accessing Members of a Structure

To access members of a structure, use the dot (.) operator:

printf("Name: %s\n", person2.name);

Memory Layout of Structures

In a structure, each member occupies its own memory, which means that the total memory used by a structure is the sum of the memory occupied by all its members.

For instance:

struct Example { int x; // 4 bytes char y; // 1 byte double z; // 8 bytes };

The size of the structure Example would be at least 13 bytes, although due to padding (alignment requirements for efficient access), it might be more than 13 bytes.

Unions in C

A union is also a user-defined data type, similar to a structure, but with a key difference: all members share the same memory location. This means that only one member can hold a value at any given time.

Defining a Union

To define a union, you use the union keyword:

union Data { int intValue; float floatValue; char str[20]; };

Here:

  • Data is a union that can store either an int, a float, or a string of characters (char str[20]), but only one of these at a time.

Declaring and Using Unions

You can declare a union variable like this:

union Data data; data.intValue = 5; printf("intValue: %d\n", data.intValue); data.floatValue = 3.14; printf("floatValue: %.2f\n", data.floatValue); // Assigning a new value overwrites the previous one strcpy(data.str, "Hello"); printf("str: %s\n", data.str);

Note: Changing one member of a union will affect all the other members because they share the same memory.

Memory Layout of Unions

In a union, all members use the same memory location, so the memory size of a union is equal to the size of its largest member.

For example:

union Example { int x; // 4 bytes char y; // 1 byte double z; // 8 bytes };

The size of the union Example is 8 bytes, since double is the largest member.


Example Comparing Structures and Unions

Consider the following structure and union:

struct Student { char name[20]; int age; float grade; }; union Worker { char name[20]; int id; float salary; };
  • The Student structure will occupy memory for name, age, and grade.
  • The Worker union will occupy memory equivalent to the largest member (name).

Use Cases

  • Structures are useful when you need to store multiple related pieces of data and access them all at the same time. For example, representing a person's profile or a student's record.
  • Unions are useful when you need to save memory and only need one member to hold a value at a time. For example, representing a value that could be of different types, like a variable that can either be an int, float, or char string.

Summary

  • Structures are used to group different types of data and each member occupies separate memory.
  • Unions allow different members to share the same memory, making it memory-efficient but allowing only one member to hold a value at a time.
  • Use structures when you need to access all members simultaneously, and unions when you need to conserve memory and know that only one value will be used at any given time.