Structure and Union in C

Structure and Union in c

In C programming, structure and union in c are user-defined data types that allow us to group variables of different types. They help to manage complex data efficiently and are foundational concepts for system programming, handling data, and creating more structured code.

What is Structure in C?

Definition of Structure in c

A structure is a user-defined data type that groups related variables of different types under a single name. It is defined using the struct keyword. Structures are particularly useful for representing a record.

Syntax: 

struct structure_name {
data_type member1;
data_type member2;
// more members
};

Example:

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

This Student structure contains three members: an integer roll_no, a string name, and a floating-point marks.

 

Accessing Members of a Structure

Members of a structure can be accessed using the dot . operator after declaring a variable of the structure type.

Example:

struct Student student1;
student1.roll_no = 1;
strcpy(student1.name, “John Doe”);
student1.marks = 85.5;

Memory Allocation in Structures

In a structure, each member has its own memory location. The total memory occupied by a structure is the sum of the memory required by each member. This leads to slightly higher memory usage but allows each variable to store different data values.

 

Union in C Programming

Definition of Union

A union is similar to a structure, but its memory is shared by all its members. Only one member can hold a value at a time, as all members use the same memory location.

Syntax:

union union_name {
data_type member1;
data_type member2;
// more members
};

Example:

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

In this example, Data can store an integer i, a float f, or a string str, but only one of these members can hold a value at any given time.

Accessing Members of a Union

Similar to structures, union members are accessed using the dot . operator.

Example:

union Data data;
data.i = 10; // Only `i` is meaningful now
data.f = 220.5; // `i`’s value is now lost
strcpy(data.str, “Hello”); // Now `f` and `i` values are lost

Memory Allocation in Union

In a union, the memory allocated is only as large as the largest member. This allows unions to be memory-efficient when storing data where only one of the variables is needed at a time.

Structure vs Union in C

Let’s look at the difference between structure and union in c with major key differences and features:

Feature Structure Union
Memory Allocation Each member has its own memory space. All members share the same memory space.
Usage All members can hold values simultaneously. Only one member can hold a value at any given time.
Access Efficiency More memory but allows multiple data points. Less memory, but overwrites data when switching.

Examples of structures in C

Example 1: Defining and Using a Structure

Program to Store and Print Student Information:

#include <stdio.h>

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

int main() {
struct Student student1;

student1.roll_no = 101;
strcpy(student1.name, “Alice”);
student1.marks = 89.5;

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

return 0;
}

Above this program defines a Student structure and uses it to store and display information. The output shows that each member is stored separately in memory.

Example 2: Defining and Using a Union

Program to Demonstrate Memory Sharing in Unions:

#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, “C Programming”);
printf(“data.str: %s\n”, data.str);

// Observe how previous data values get overwritten:
printf(“After changing str, data.i: %d and data.f: %.1f\n”, data.i, data.f);

return 0;
}

This program demonstrates that each time a new value is assigned to a union member, the previous value is lost. This is because all members of the union share the same memory.

Example 3: Structure Array for Managing Multiple Records

When working with multiple entries of similar data types (e.g., a list of employees), structures can be used to create a structured array that simplifies data handling and manipulation.

 Example: Employee Management System 

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

struct Employee {
int id;
char name[30];
float salary;
};

int main() {
struct Employee employees[3];

// Initializing employee records
employees[0].id = 101;
strcpy(employees[0].name, “Alice”);
employees[0].salary = 50000.0;

employees[1].id = 102;
strcpy(employees[1].name, “Bob”);
employees[1].salary = 45000.0;

employees[2].id = 103;
strcpy(employees[2].name, “Charlie”);
employees[2].salary = 47000.0;

// Display employee records
for (int i = 0; i < 3; i++) {
printf(“Employee ID: %d\n”, employees[i].id);
printf(“Name: %s\n”, employees[i].name);
printf(“Salary: %.2f\n\n”, employees[i].salary);
}

return 0;
}

Here, an array of structures is used to store information about multiple employees. This setup is beneficial for applications that require managing numerous entries and processing them in a structured way.

FAQs on Structures and Unions in C Programming

1. What is a structure in C programming?

A structure in C programming is a user-defined data type that groups variables of different types under a single name. Structures are used to represent a record, making it easier to handle complex data. For example, you could create a structure to store information about a student with fields like name, age, and grade.


2. How do you declare a structure in C?

To declare a structure in C, you use the struct keyword followed by the structure name and the list of variables (called members) within curly braces. For example:

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

Here, Student is a structure containing an integer, a character array, and a floating-point number.


3. How is a union different from a structure in C?

In C, a union is similar to a structure but with a key difference: while each member in a structure has its own memory, all members in a union share the same memory. This means only one union member can hold a value at any time. Structures allow each variable to store values simultaneously, whereas unions overwrite previous data with each new assignment.


4. When should I use a union instead of a structure in C?

Use a union when you need to store different types of data in a single variable, but only one data type is needed at any given time. Unions are useful for memory efficiency in cases where only one field will be used at a time, such as handling different data formats or interpreting binary data.


5. How do you access members of a structure in C?

To access members of a structure in C, you create a structure variable and use the dot . operator with the variable name. For example:

struct Student student1;
student1.roll_no = 101;
strcpy(student1.name, “Alice”);
student1.marks = 88.5;

That’s all guys, Structures and unions in C are powerful tools for handling complex data more efficiently. Understanding the differences between structures and unions, especially in terms of memory management and access is one of the most crucial things and this way structure & union are useful.

Thank You!

Leave a Reply

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

Featured Posts: