Unit-IV Structure and Unions
Unit-IV Structure and Unions
A structure in C is a user-defined data type that groups different data types into a single unit. It
is a way to logically organize data that represents real-world entities. Structures are declared
using the struct keyword.
Why Structures?
● A student record may include a name (string), roll number (integer), and marks (float).
● A book entity may include a title, author, price, and publication year.
Using structures helps in managing and accessing such composite data efficiently.
● Declaration: Defining a structure specifies its layout but does not allocate memory.
● Initialization: Creating a variable of the structure type and assigning values to its
members.
Syntax
struct StructureName {
dataType member1;
dataType member2;
...
};
Real-Life Applications
struct Student {
char name[50];
int rollNumber;
float marks;
};
int main() {
return 0;
Output:
Name: Alice
Marks: 95.50
Explanation:
Here, a Student structure is defined, and an instance is initialized with values. The printf
statements access and display the structure members.
struct Book {
char title[50];
char author[50];
float price;
};
int main() {
// Manual Initialization
scanf("%s", b1.title);
scanf("%s", b1.author);
scanf("%f", &b1.price);
printf("\nBook Details:\n");
Output (Example):
Book Details:
Title: Programming_C
Author: Dennis
Price: 399.50
Explanation:
This example demonstrates how a structure's members are manually initialized using user
input.
struct Employee {
char name[50];
int id;
float salary;
};
int main() {
};
return 0;
Output:
Employee 1:
Name: John
ID: 101
Salary: 50000.00
Employee 2:
Name: Jane
ID: 102
Salary: 60000.00
Explanation:
An array of Employee structures is initialized with data. A loop is used to display the details of
each employee.
struct Point {
int x, y;
};
int main() {
printPoint(p1);
return 0;
}
Output:
Explanation:
Here, a Point structure is passed as a parameter to a function, showcasing how structures
can be passed and used in functions.
2. Nested Structures
Definition and Background
Nested structures are structures within structures, allowing hierarchical or complex relationships
between data types.
struct Address {
char city[50];
int zipCode;
};
struct Person {
char name[50];
struct Address addr;
};
int main() {
return 0;
Output:
Name: Alice
Explanation:
Here, the Address structure is nested inside the Person structure to represent a person’s
details including their address.
3. Arrays of Structures
Definition and Background
Arrays of structures allow storing and accessing multiple instances of a structure in a sequential
manner.
Example 1: Students with Arrays
#include <stdio.h>
struct Student {
char name[50];
int rollNo;
float marks;
};
int main() {
{"Alice", 1, 90.5},
{"Bob", 2, 85.0},
{"Charlie", 3, 88.5}
};
return 0;
Output:
Name: Alice, Roll No: 1, Marks: 90.50
Structures in C are user-defined data types that group related variables of different data types
under a single name. Functions are blocks of code designed to perform specific tasks.
Combining structures and functions allows better modularity, code organization, and
manipulation of complex data.
Real-life Applications
1. Student Records Management: Storing and processing student details like name, roll
number, and marks.
2. Employee Database: Storing and calculating employee salaries, attendance, and
performance.
3. Graphics Systems: Managing points, colors, and shapes.
Output:
Name: Alice
Roll: 1
Marks: 95.50
Explanation: The Student structure is passed to the display function by value. The function
prints the structure's members.
int main() {
struct Employee emp = {101, 5000.0};
updateSalary(&emp);
printf("Updated Salary: %.2f\n", emp.salary);
return 0;
}
Output:
int main() {
struct Point pt = createPoint(5, 10);
printf("Point: (%d, %d)\n", pt.x, pt.y);
return 0;
}
Output:
Explanation: The createPoint function creates and returns a structure. This technique is
useful for initialization.
int main() {
struct Product p[2] = {{101, 25.5}, {102, 50.0}};
displayProducts(p, 2);
return 0;
}
Output:
5. Self-Referential Structures
Definition and Background
Real-life Applications
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 = (struct Node *)malloc(sizeof(struct Node));
struct Node *second = (struct Node *)malloc(sizeof(struct Node));
struct Node *third = (struct Node *)malloc(sizeof(struct Node));
printList(head);
return 0;
}
Output:
Explanation: Each node points to the next node, forming a chain. This is the basis of linked
lists.
struct Node {
int data;
struct Node *prev;
struct Node *next;
};
int main() {
struct Node *head = (struct Node *)malloc(sizeof(struct Node));
struct Node *second = (struct Node *)malloc(sizeof(struct Node));
printList(head);
return 0;
}
Output:
12
Explanation: Each node points to both its predecessor and successor, enabling traversal in
both directions.
Other topics, Unions and Arrays of Union Variables, will follow a similar format with detailed
notes and examples. Would you like me to continue or adjust the detail level?
6. Unions
A union in C is a user-defined data type that allows storing different data types in the same
memory location. Unlike structures, all members of a union share the same memory space,
meaning only one member can hold a value at a time. The size of a union is determined by the
size of its largest member.
Real-life Applications
1. Memory Optimization: Useful in embedded systems where memory is limited.
2. Variant Data Storage: Storing values of different types (e.g., int, float) in the same
location.
3. Device Drivers: Handling hardware register data that may represent different
functionalities.
union Data {
int intValue;
float floatValue;
};
int main() {
union Data d;
d.intValue = 10;
printf("Integer value: %d\n", d.intValue);
d.floatValue = 20.5;
printf("Float value: %.2f\n", d.floatValue);
printf("Integer value after float assignment: %d\n", d.intValue);
return 0;
}
Output:
Integer value: 10
Float value: 20.50
Integer value after float assignment: 1101529088
Explanation: The floatValue overwrites the memory of intValue, demonstrating how union
members share memory.
union DeviceStatus {
int errorCode;
float temperature;
};
int main() {
union DeviceStatus status;
enum Mode currentMode = TEMP;
if (currentMode == ERROR) {
status.errorCode = 404;
printf("Error Code: %d\n", status.errorCode);
} else {
status.temperature = 36.5;
printf("Temperature: %.2f\n", status.temperature);
}
return 0;
}
Output:
Temperature: 36.50
Explanation: Union stores different types based on the current mode, optimizing memory for
conditional data.
union InputOutput {
char input[50];
int outputCode;
};
int main() {
union InputOutput io;
printf("Enter a string: ");
scanf("%s", io.input);
printf("You entered: %s\n", io.input);
io.outputCode = 200;
printf("Output Code: %d\n", io.outputCode);
return 0;
}
Output:
Explanation: Demonstrates switching between string and integer values using a union.
union Nested {
union {
int intData;
float floatData;
} data;
char charData;
};
int main() {
union Nested n;
n.data.intData = 5;
printf("Integer data: %d\n", n.data.intData);
n.charData = 'A';
printf("Char data: %c\n", n.charData);
return 0;
}
Output:
Integer data: 5
Char data: A
Explanation: Shows how nested unions operate by sharing memory among inner and outer
union members.
7. Arrays of Union Variables
Real-life Applications
1. Sensor Data: Managing heterogeneous sensor data types (e.g., temperature, pressure,
and humidity).
2. Network Protocols: Storing message headers of varying formats in network
communication.
3. Data Compression: Handling dynamic data types in compression algorithms.
union Item {
int id;
float price;
char name[20];
};
int main() {
union Item items[3];
items[0].id = 101;
items[1].price = 15.75;
sprintf(items[2].name, "Pen");
return 0;
}
Output:
Item ID: 101
Item Price: 15.75
Item Name: Pen
Explanation: Each union in the array stores a different type of data, demonstrating how unions
in arrays operate.
union Data {
int intValue;
float floatValue;
};
int main() {
union Data dataArr[2];
printf("Enter an integer: ");
scanf("%d", &dataArr[0].intValue);
printf("Enter a float: ");
scanf("%f", &dataArr[1].floatValue);
return 0;
}
Output:
Enter an integer: 10
Enter a float: 20.5
Integer: 10
Float: 20.50
Explanation: The array holds union elements, and user input dynamically assigns values to
them.
Example 3: Managing Sensor Readings
#include <stdio.h>
union Sensor {
int humidity;
float temperature;
};
int main() {
union Sensor sensors[2];
sensors[0].humidity = 60;
sensors[1].temperature = 22.5;
return 0;
}
Output:
Humidity: 60%
Temperature: 22.50°C
Explanation: Each union in the array stores a specific type of sensor data.
union Data {
int id;
float grade;
};
int main() {
union Data students[3];
students[0].id = 1;
students[1].grade = 85.5;
Output:
Student ID: 1
Student Grade: 85.50
Explanation: Demonstrates switching between id and grade for student records stored in an
array of unions.
8. Unions Inside Structures
Definition and Background
A union in C is a special data type where all members share the same memory location. This
means only one member of a union can store a value at any given time. A structure, on the
other hand, allows each member to have its own memory location, meaning all members can
store values simultaneously.
When we combine a union inside a structure, it allows us to group multiple data types in a
flexible and efficient way. This combination is useful when we need to store different types of
information based on certain conditions, while also saving memory.
Real-Life Example
Imagine a student record system where some students have their marks stored as
percentages (e.g., 85.5%), while others have grades stored as characters (e.g., 'A'). Using a
union within a structure, we can store either marks or grades for a student, depending on the
requirement, without wasting memory.
struct Student {
char name[20];
int rollNumber;
union {
float percentage;
char grade;
} result;
};
int main() {
struct Student student1 = {"Alice", 1, .result.percentage = 92.5};
struct Student student2 = {"Bob", 2, .result.grade = 'B'};
return 0;
}
Output:
Explanation:
● Here, each student has a union called result inside their structure.
● For Alice, the percentage is stored in result.percentage.
● For Bob, the grade is stored in result.grade.
The union ensures that only one type of result is stored at a time, saving memory.
struct Employee {
char name[20];
int id;
union {
int hoursWorked; // For hourly employees
float monthlySalary; // For salaried employees
} payment;
};
int main() {
struct Employee emp1 = {"John", 1001, .payment.hoursWorked = 160};
struct Employee emp2 = {"Emma", 1002, .payment.monthlySalary = 5000.50};
return 0;
}
Output:
Explanation:
struct Sensor {
char type[10];
int id;
union {
int integerValue; // For simple measurements
float floatValue; // For precise measurements
} data;
};
int main() {
struct Sensor sensor1 = {"Pressure", 101, .data.integerValue = 100};
struct Sensor sensor2 = {"Temperature", 102, .data.floatValue = 37.5};
return 0;
}
Output:
Explanation:
● Depending on the sensor type, we store data as either an integer (for simpler readings)
or a float (for precise measurements).
● This setup optimizes memory usage without compromising functionality.
A structure inside a union allows grouping multiple related variables (as a structure) but
ensures only one structure’s data is active at any time within the union. This setup is useful
when dealing with complex data formats that vary depending on the situation.
Real-Life Example
Imagine a network packet that can either contain TCP header information (like source and
destination ports) or IP header information (like IP version and time-to-live). Using a structure
inside a union, we can model this packet to switch between the two formats seamlessly.
int main() {
union Packet packet;
// TCP header
packet.tcp.srcPort = 8080;
packet.tcp.destPort = 80;
// IP header
packet.ip.version = 4;
packet.ip.ttl = 64;
return 0;
}
Output:
Explanation:
union Media {
struct {
int duration; // in seconds
int bitrate; // in kbps
} audio;
struct {
int width;
int height;
} video;
};
int main() {
union Media media;
// Audio metadata
media.audio.duration = 300;
media.audio.bitrate = 128;
// Video metadata
media.video.width = 1920;
media.video.height = 1080;
return 0;
}
Output:
Explanation:
An enumerated data type (enum) in C is used to define a set of named integer constants. It
helps make programs more readable and maintainable by replacing literal numbers with
meaningful names. By default, the enumeration constants start from 0 and increment by 1 for
each subsequent value, but they can also be explicitly assigned specific values.
Real-Life Example
Enums are widely used in situations where we need to represent a set of predefined options.
For example:
● Days of the week: Instead of using numbers like 0 for Sunday and 6 for Saturday, we
can use SUNDAY, MONDAY, etc.
● Traffic light system: Using enums like RED, YELLOW, and GREEN makes the code
easier to understand and debug.
int main() {
enum Day today;
today = TUESDAY;
if (today == TUESDAY) {
printf("Today is Tuesday. Time for team meeting!\n");
}
return 0;
}
Output:
Explanation:
● The enum Day assigns numeric values to the days (SUNDAY = 0, MONDAY = 1, etc.).
● The program uses the named constants to check if it’s Tuesday and prints appropriate
messages.
int main() {
enum TrafficLight currentSignal;
currentSignal = RED;
displaySignal(currentSignal);
currentSignal = GREEN;
displaySignal(currentSignal);
return 0;
}
Output:
Explanation:
int main() {
enum ErrorCode status;
status = SUCCESS;
checkStatus(status);
status = WARNING;
checkStatus(status);
status = ERROR;
checkStatus(status);
return 0;
}
Output:
Explanation:
● The enum ErrorCode assigns meaningful names to numeric values for error codes.
● The program uses these values to display appropriate messages.
enum Month { JANUARY = 1, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST,
SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER };
int main() {
enum Month birthMonth = MAY;
return 0;
}
Output:
● The enum Month assigns numeric values to months, starting from 1 for January.
● The program uses these values to identify the birth month and season.
1. Readability: Enums replace numbers with descriptive names, making the code easier to
understand.
2. Maintainability: Changes to enum values are centralized, reducing errors.
3. Error Prevention: By limiting valid values to a predefined set, enums help catch invalid
inputs.