C ProgrammingUnit 98 min read
Structures & Unions: Definitions, Syntax, Applications & Comparisons
Unit 9 of C Programming covers structures (custom data types grouping related variables), unions (memory-sharing alternatives), nested structures, typedef, and their applications in real-world data modeling. Learn syntax, memory allocation, and how to use pointers with structures—essential for exam questions on record
TAKEAWAYS:
- Structures group heterogeneous data (e.g.,
studentwithroll,name,marks) under one name, while unions share memory for one active member at a time. - Use
typedefto simplify structure declarations (e.g.,typedef struct { ... } Student;). - Pointers to structures (
struct *ptr) enable dynamic memory allocation and efficient passing to functions. - Unions save memory but risk data corruption if misused (e.g., storing an
intafter achar). - Real-world uses include employee databases (structures), network packet headers (unions), and game entity systems.
1. Structures: Custom Data Types
A structure (struct) is a user-defined data type that groups related variables of different types under a single name. It mimics real-world entities (e.g., a Student has a roll, name, and marks).
Syntax
struct structure_name {
data_type member1;
data_type member2;
...
};
Example: Student Record
struct Student {
int roll;
char name[50];
float marks;
};
How to Use Structures
- Declare a structure variable:
struct Student s1; - Access members using the dot (
.) operator:s1.roll = 101; strcpy(s1.name, "Ramesh"); s1.marks = 85.5; - Initialize while declaring:
struct Student s2 = {102, "Sita", 90.0};
Memory Layout
All members are stored contiguously in memory. The size of a structure is the sum of its members' sizes + padding (for alignment).
printf("%lu", sizeof(struct Student)); // Output: 56 (assuming 4-byte int, 50-byte char[], 4-byte float + padding)
2. Structures vs. Unions: Key Differences
| Feature | Structure (struct) |
Union (union) |
|---|---|---|
| Memory | Allocates space for all members | Allocates space for the largest member |
| Access | All members can be accessed simultaneously | Only one member holds valid data at a time |
| Use Case | Grouping related data (e.g., Employee) |
Memory-efficient alternatives (e.g., IPv4/IPv6 headers) |
| Syntax | struct keyword |
union keyword |
| Example | struct { int a; float b; }; |
union { int a; float b; }; |
3. Unions: Memory Optimization
A union shares the same memory location for all its members. Only one member can hold a value at a time.
Syntax
union Data {
int i;
float f;
char str[20];
};
Example: Network Packet Header
union Header {
struct {
unsigned int ipv4;
} ipv4;
struct {
unsigned int ipv6[8];
} ipv6;
};
- If the packet is IPv4,
ipv4.ipv4holds the address. - If IPv6,
ipv6.ipv6holds the address (same memory location).
4. Nested Structures and typedef
Nested Structures
Structures can contain other structures (e.g., Address inside Student).
struct Address {
char city[50];
int pincode;
};
struct Student {
int roll;
char name[50];
struct Address addr; // Nested structure
};
typedef for Simplicity
Replace struct Student with a shorter name:
typedef struct {
int roll;
char name[50];
} Student; // Now declare as: Student s1;
5. Pointers to Structures
Pointers to structures (struct *ptr) enable:
- Dynamic memory allocation (
malloc/calloc). - Efficient function arguments (pass by reference).
Example: Dynamic Array of Structures
Student *ptr = (Student*)malloc(10 * sizeof(Student));
for (int i = 0; i < 10; i++) {
ptr[i].roll = i + 1;
strcpy(ptr[i].name, "StudentX");
}
Accessing Members via Pointer
printf("%s", ptr->name); // Equivalent to (*ptr).name
6. Real-World Applications
In Nepal
eSewa/Khalti Transactions
- Uses structures to store
Transactionrecords:struct Transaction { char user_id[20]; float amount; char status[10]; // "Success"/"Failed" }; - Unions optimize memory for
PaymentMethod(credit/debit/cash).
- Uses structures to store
Ncell Billing System
- Structures model
Customer:struct Customer { char phone[15]; float balance; char plan[20]; }; - Pointers to structures enable dynamic updates (e.g., adding new customers).
- Structures model
NEPSE Stock Market
- Unions represent
OrderType(buy/sell):union Order { struct { float buy_price; } buy; struct { float sell_price; } sell; };
- Unions represent
Worked Example: Daraz Order Queue
Problem: Simulate a queue of orders where each order has order_id, product, and status.
Solution: Use a structure with a linked list.
struct Order {
int order_id;
char product[50];
char status[10];
struct Order *next;
};
Visualization (After Insertion):
graph LR
A["Order 101: Laptop"] --> B["Order 102: Phone"]
B --> C["Order 103: Book"]
C -->|"NULL"| D["End"]7. Exam-Style Programs
Program 1: Filter Students by Marks
Task: Read 35 students and display those with >250 marks.
#include <stdio.h>
#define N 35
struct Student {
int roll;
char name[50];
float marks;
};
int main() {
struct Student students[N];
for (int i = 0; i < N; i++) {
scanf("%d %s %f", &students[i].roll, students[i].name, &students[i].marks);
}
for (int i = 0; i < N; i++) {
if (students[i].marks > 250) {
printf("%s\n", students[i].name);
}
}
return 0;
}
Program 2: Sort Books by Title (Using Pointers)
Task: Sort 100 books by title (descending).
#include <stdio.h>
#include <string.h>
struct Book {
int bid;
char title[50];
float price;
int pages;
};
void sortBooks(struct Book *books, int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (strcmp(books[j].title, books[j+1].title) < 0) {
struct Book temp = books[j];
books[j] = books[j+1];
books[j+1] = temp;
}
}
}
}
Trace for sortBooks (First 2 Swaps):
| Step | books[0].title |
books[1].title |
Action |
|---|---|---|---|
| 1 | "C Programming" | "Data Science" | Swap (lex order: D > C) |
| 2 | "Data Science" | "C Programming" | No swap (now ordered) |
8. Common Pitfalls
- Forgetting to Initialize:
struct Student s; // Uninitialized! Use `s.roll = 0;` or `{0}`. - Union Data Corruption:
union Data d; d.i = 10; // Valid d.f = 3.14; // Overwrites `i`! Use only one member at a time. - Pointer Arithmetic Errors:
struct Student *ptr = students; ptr++; // Moves by `sizeof(struct Student)`, not 1 byte!
Exam Tip
Structure vs. Union:
- Always compare memory usage and access rules in exam questions.
- Example answer snippet:
"A structure allocates memory for all members simultaneously, while a union shares memory, allowing only one member to hold data at a time. For example, a
struct Employeestoresname,salary, andageseparately, whereas aunion Packetfor network data might hold either an IPv4 or IPv6 address in the same memory location."
Programming Questions:
- Input/Output: Use
scanf/printffor all members. - Filtering/Sorting: Loop through the array/linked list and apply conditions.
- Pointers: Use
->for pointer access (e.g.,ptr->name).
- Input/Output: Use
Real-World Tie-Ins:
- If asked about applications, mention:
- Structures: Database records (e.g.,
Customerin banks), game entities. - Unions: Network protocols (e.g.,
IPv4/IPv6headers), variant data types.
- Structures: Database records (e.g.,
- If asked about applications, mention:
Code Structure:
- Declare structures before
main(). - Use
typedefto avoidstructkeyword repetition in large programs.
- Declare structures before
Visual Summary:
classDiagram
class Structure {
+All members allocated
+Access all members
}
class Union {
+Only largest member allocated
+Access one member at a time
}
Structure --> "Inherits" Union : "Memory sharing"
Structure : +struct Keyword
Union : +union KeywordBased on the TU BCA syllabus for C Programming (CACS151), unit 9.
Discussion
Loading…