In this tutorial, we will learn about structures and unions in C. A structure lets you group different types of data together, and each piece of data gets its own memory. A union also groups data, but all the data shares the same memory, so only one piece of data can be stored at a time. We will show you how to use and work with both structures and unions in C.
Contents:
- What are Structures in C?
- Defining a Structure in C
- Array of Structures in C
- Nested Structures in C
- Self-Referential Structures in C
- What are Unions in C?
- Defining a Union in C
- Differences Between Structures and Unions in C
- Applications of Structures in C
- Applications of Unions in C
- FAQs on Structures and Unions in C
What are Structures in C?
In C, a structure is a custom data type that groups different types of data under one name. It helps to store related variables together in an organized way.
Key Features of Structures:
- Heterogeneous Data Storage: Unlike arrays, which store only one type of data, structures can store different types of data.
- Memory Allocation: Each part of the structure has its own memory space.
- Accessing Members: You can use the dot (.) operator to access each part of the structure.
- Supports Arrays of Structures: You can use an array to create multiple records.
Defining a Structure in C
In C, a structure is defined using the struct keyword.
Syntax:
struct StructureName { data_type member1; data_type member2; ... };
Example: Defining and Using a Structure
#include <stdio.h> // Define a structure for certification details struct Certification { char candidateName[50]; char course[30]; int score; }; int main() { // Declare and initialize a structure variable struct Certification cert = {"Pooja", "C Programming", 95}; // Display certification details printf("Sanfoundry Certification Details\n"); printf("--------------------------------\n"); printf("Candidate Name : %s\n", cert.candidateName); printf("Course : %s\n", cert.course); printf("Score : %d%%\n", cert.score); return 0; }
Output:
Sanfoundry Certification Details -------------------------------- Candidate Name : Pooja Course : C Programming Score : 95%
This C program creates a structure called Certification to store a candidate’s name, course, and score. In the main() function, it sets values for these details. Then, it prints the candidate’s name, course, and score on the screen in a simple format.
Array of Structures in C
An array of structures in C is a collection of structure variables stored sequentially in memory. It is used when you need to store multiple records of the same type.
Syntax:
struct StructureName { data_type member1; data_type member2; // More members if needed }; struct StructureName arrayName[array_size];
Example:
#include <stdio.h> // Define a structure for quiz results struct QuizResult { char participant[50]; int score; }; int main() { // Declare an array of structures struct QuizResult results[3] = { {"David", 95}, {"Sreeja", 88}, {"Nitesh", 92} }; // Display quiz results printf("Sanfoundry Quiz Results\n"); printf("----------------------------\n"); for (int i = 0; i < 3; i++) { printf("Participant: %s, Score: %d\n", results[i].participant, results[i].score); } return 0; }
Output:
Sanfoundry Quiz Results ---------------------------- Participant: David, Score: 95 Participant: Sreeja, Score: 88 Participant: Nitesh, Score: 92
This C program defines a structure called QuizResult to store the participant’s name and score. In the main() function, it declares an array of structures called results to hold quiz results for three participants: David, Sreeja, and Nitesh. The program then uses a loop to print the name and score of each participant in a clear format.
Nested Structures in C
A nested structure in C is a structure that contains another structure as a member. It helps in organizing complex data by allowing hierarchical structuring.
Syntax:
struct Outer { data_type variable1; struct Inner { data_type variable2; } innerVar; };
Example:
#include <stdio.h> // Define an outer structure struct Certification { char name[50]; struct Score { int marks; char grade; } result; }; int main() { // Declare and initialize a nested structure struct Certification student = {"Harsh", {90, 'A'}}; // Display the certification details printf("Sanfoundry Certification Details:\n"); printf("Participant: %s\n", student.name); printf("Marks: %d\n", student.result.marks); printf("Grade: %c\n", student.result.grade); return 0; }
Output:
Sanfoundry Certification Details: Participant: Harsh Marks: 90 Grade: A
This C program defines a structure called Certification with a nested structure Score. The Certification structure stores a participant’s name, and the Score structure stores the marks and grade. The program creates a variable student with the name “Harsh,” marks 90, and grade ‘A’. It then prints the participant’s name, marks, and grade.
Self-Referential Structures in C
A self-referential structure is a structure that includes a pointer to an instance of the same structure type. These structures are commonly used in linked lists, trees, and other dynamic data structures.
Syntax:
struct Node { int data; struct Node *next; // Pointer to another instance of struct Node };
Example: Implementing a Simple Linked List Node
#include <stdio.h> #include <stdlib.h> // Define a self-referential structure struct Node { int data; struct Node *next; // Pointer to the next node }; int main() { // Creating nodes dynamically struct Node *head = (struct Node*)malloc(sizeof(struct Node)); struct Node *second = (struct Node*)malloc(sizeof(struct Node)); // Initializing data head->data = 10; head->next = second; second->data = 20; second->next = NULL; // Displaying the values printf("Sanfoundry Linked List Example:\n"); printf("First Node Data: %d\n", head->data); printf("Second Node Data: %d\n", second->data); // Free allocated memory free(head); free(second); return 0; }
Output:
Sanfoundry Linked List Example: First Node Data: 10 Second Node Data: 20
What are Unions in C?
A union in C is a special 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, and the size of the union is determined by the largest member.
Defining a Union in C
A union is defined using the union keyword, similar to how a structure (struct) is defined.
Syntax:
union UnionName { data_type member1; data_type member2; ... };
Example: Declaring and Using a Union
#include <stdio.h> // Define a union for a Sanfoundry certification test result union TestResult { int score; char grade; }; int main() { union TestResult sanfoundry; // Assign and print score sanfoundry.score = 85; printf("Sanfoundry Quiz Score: %d\n", sanfoundry.score); // Assign and print grade (overwrites score due to shared memory) sanfoundry.grade = 'A'; printf("Sanfoundry Certification Grade: %c\n", sanfoundry.grade); // Previous score is now overwritten, showing the union's behavior printf("Updated Score (Corrupted due to Union behavior): %d\n", sanfoundry.score); return 0; }
Output:
Sanfoundry Quiz Score: 85 Sanfoundry Certification Grade: A Updated Score (Corrupted due to Union behavior): 65
This C program uses a union called TestResult. The union can store either a score or a grade, but not both at the same time. First, it stores the score 85 and prints it. Then, it stores the grade ‘A’, which replaces the score. When it prints the score again, it shows the overwritten value.
Differences Between Structures and Unions in C
Here’s a structured comparison between Structures (struct) and Unions (union) in C:
Feature | Structure (struct) | Union (union) |
---|---|---|
Memory Allocation | Allocates separate memory for each member. | All members share the same memory space. |
Calculation of Size | Size = sum of all members. | Size = size of the largest member. |
Access | All members can be accessed simultaneously. | Only one member can store a valid value at a time. |
Value Retention | Each member retains its own value. | Storing a new value overwrites previous data. |
Example Size (for int, float, char[20]) | Size = 28 bytes (4+4+20). | Size = 20 bytes (largest member). |
Use Case | When all members are needed at once. | When only one member is needed at a time. |
Speed | Faster (direct access to all members). | Slightly slower (only one member usable at a time). |
Memory Efficiency | Uses more memory. | Saves memory by sharing space. |
Example Applications | Employee records, student details, car specs. | Symbol tables, compiler data types, device drivers. |
Supported Nesting | Yes (can contain structures and unions). | Yes (can contain structures and unions). |
Applications of Structures in C
- Grouping Related Data: Structures combine different types of data into one unit. This is helpful for things like students, employees, and customers.
- Database Records: Structures help manage database records, making it easier to store and retrieve data.
- Data Processing: Structures are used to work with data files, network packets, and formats like JSON or XML.
- System Programming: Structures help operating systems manage processes, system calls, and hardware tasks.
- Networking: Structures define network headers and help manage data packets in networking.
Applications of Unions in C
- Memory Optimization: Unions allow different variables to use the same memory space, saving memory in small systems like microcontrollers.
- Handling Different Data Types: Unions store different data types in one memory space, which is useful in hardware and data conversion.
- Bit Manipulation: Unions help modify specific bits in hardware registers using bit-fields.
- Device Drivers: Unions are used in low-level programming and controlling devices efficiently.
- APIs and Hardware: Unions help manage data in C-based APIs and during hardware access, making data handling easier.
FAQs on Structures and Unions in C
1. What is a structure in C?
A structure in C is a user-defined data type that allows grouping different data types under a single name. It is used to organize complex data efficiently.
2. What is a union in C?
A union is a special data type in C that allows multiple variables to share the same memory space. Only one member can store a value at a time, making unions memory-efficient.
3. When should I use a structure instead of a union?
Use a structure when you need to store multiple pieces of related data independently. Examples include student records, employee details, and product catalogs.
4. When should I use a union instead of a structure?
Use a union when memory optimization is crucial, and only one value is needed at a time. Examples include embedded systems, hardware registers, and variant data storage.
5. Can a structure contain a union?
Yes, a structure can contain a union as a member. This is useful when defining complex data types that require memory-efficient storage.
6. Can a union contain a structure?
Yes, a union can contain a structure, but since a union shares memory for all its members, you must carefully manage data assignment to avoid overwriting values.
7. Can we use pointers with structures and unions?
Yes, pointers can be used with both structures and unions to dynamically allocate memory and manipulate data efficiently.
8. Are structures and unions compatible with file handling in C?
Yes, structures and unions are widely used in file handling, particularly when reading and writing binary data.
Key Points to Remember
Here is the list of key points we need to remember about “Structures and Unions in C”.
- Structures allow grouping different types of data under one name, each with its own memory space.
- In unions, all members share the same memory space, so only one member can hold a value at any time.
- In structures, each member has its own memory space, while in unions, all members share a common memory location.
- Structures allow accessing all members at the same time, whereas unions allow accessing only one member at a time.
- Structures can contain other structures as members, allowing for hierarchical data representation.
- You can store multiple records of the same type using arrays of structures.
- Structures can have pointers to themselves, commonly used in dynamic data structures like linked lists.
- Structures are useful for grouping related data, while unions are great for memory optimization and handling different data types in embedded systems or hardware programming.
- Check Computer Science Books
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Apply for C Internship
- Practice BCA MCQs