Structures and Unions in C Programming PDF

Summary

This document provides a comprehensive introduction to structures and unions in C programming. It explains the concept of structures as user-defined data types capable of holding various data types, and the concept of unions which allow multiple variables of different data types to use the same memory location. Various examples and syntax are presented to illustrate the usage.

Full Transcript

## What is a Structure? - A structure can be defined as a single entity holding variables of different data types that are logically related to each other. - Structure is a user-defined data type in C language which allows us to combine data of different types together. - Structure is a collection...

## What is a Structure? - A structure can be defined as a single entity holding variables of different data types that are logically related to each other. - Structure is a user-defined data type in C language which allows us to combine data of different types together. - Structure is a collection of variables of similar or different types under a single name. - A structure is a collection of related data items (not necessarily of the same type) in which each item is identified by its own identifier, each of which is known as a member of the structure. ## Syntax The syntax of defining a structure is: ``` struct <structure_name> { data-type member1; data-type member2; }; ``` ### Description of the Syntax - **Keyword struct**: The keyword struct is used at the beginning while defining a structure. - **structure_name**: This is the name of the structure which is specified after the keyword struct. - **data-type**: The data type indicates the type of the data members of the structure. A structure can have data members of different data types. - **member**: This is the name of the data member of the structure. Any number of data members can be defined inside a structure. Each data member is allocated a separate space in the memory. ### Example 1 ``` struct emp { char ename [20]; int eno; float esal; }; ``` ### Example 2 ``` struct address { char name [30]; char street [20]; char city [15]; char state [15]; int pincode; }; ``` ### Declaration of Structure Variables with Structure Definition This way of declaring a structure variable is suitable when there are few variables declared. **Syntax** The syntax of declaration of structure variables with structure definition: ``` struct <structure_name> { data-type member1; data-type member2; } struct_var1, struct_var2; ``` **Example** ``` struct emp{ char ename [20]; int eno; float esal; }e1, e2; ``` ### Declaration of Structure Variables Separately This way of creating structure variables is preferred when multiple variables are required to be declared. The structure variables are declared outside the structure. **Syntax** The syntax of declaration of structure variables with structure definition: ``` struct <structure_name> { data-type member1; data-type member2; }; struct <structure_name> struct_var1, struct_var2,....; ``` ### Example ``` struct emp { char ename[20]; int eno; float esal; }; struct emp e1,e2,e3; ``` ### Array of Structures So far, we learned how to declare and initialize a set of structure variables individually like: ``` struct marks { char sname[20]; int subject[3]; int total; }; struct marks student1 = {"Mani", 60,95,85,0}; struct marks student2 = {"Srikanth", 80, 80,60,0}; struct marks student3 = {"Bhagya", 70,60,40,0}; ``` In order to declare or initialize a set of structure variables at a time in a single statement rather than one-by-one, C language permits an **Array of structures**, where each element of the array represents a different structure variable. ``` struct marks student [3] = { {"Mani", {60,95,85},0}, {"Srkanth", {80,80,60},0}, {"Bhagya", {70,60,40},0} }; ``` ## Union A union is a user-defined data type similar to structure except for one key difference. Structures allocate enough space to store all their members, whereas unions can only hold one member value at a time. The declaration for a union is identical to that of a structure, except that the keyword union must be substituted in place of struct. In structure each member has its own storage space; but in the case of union, all the members share only one common storage space, which means all the union members use the same location. ### What is a Union? Union can be defined as a user-defined data type which is a collection of different variables of different data types in the same memory location. The union can have many members, but only one member can contain a value at a particular point in time. ### Defining Union The syntax of union follows the same syntax of structure but the keyword union must be substituted in place of struct. **Syntax** The syntax of defining a union is: ``` union <union_name> { data-type member1; data-type member2; }; ``` ### Description of the Syntax - **Keyword union**: The keyword union is used at the beginning while defining a structure. - **union_name**: This is the name of the union which is specified after the keyword union. - **data-type**: The data type indicates the type of the data members of the union. A union can have data members of different data types. - **member**: This is the name of the data member of the union. Any number of data members can be defined inside a union. All data members share the common memory location. The compiler will allocate storage space for the union variable to accommodate the largest member of the union. Unlike accessing all the members of structure at a time, one member should be accessed at a time in union. ### Declaration of Union Variables Once the union data type is created, variables can be declared as shown below: ``` union student{ int age; char sex; float percent; } u1, u2; union student S1, S2, S3; ``` ### Advantages of Structures - Structure helps to construct a complex data type which is more meaningful. - Structures are heterogeneous collection of data items. Structure allows us to create user-defined data type which can store items with different data types. - It is very easy to maintain as we can represent the whole record or entity by using a single name. - We can pass complete set of records to any function using a single parameter. For example, passing structure variables to the function. - A function can return set of records by returning structure variables. - We can use an array of structure to store more records with similar types. - It reduces the complexity of the program. - It eliminates lots of burden while dealing with records which contain heterogeneous data items, thereby increasing productivity. - It enhances code readability. ### Difference between Arrays and Structures | Feature | Array | Structure | |---|---|---| | Data Type | Homogeneous | Heterogeneous | | Element Access | Subscripts [] | Dot Operator . | | Pointer | Yes | No | | Size | Fixed | Variable | | Memory Allocation | Continuous | May be continuous or not | | Element Access | By Index | By Name | | Declaration | No keyword | Keyword 'struct' | | Access Time | Fast | Slower | ## Program to Demonstrate Data Retrieval in Unions ```c #include <stdio.h> union demo { int age; char gender; float percent; }; int main() { union demo d; d.age = 15; d.gender = 'M'; d.percent = 38.22; printf("%f \n", d.percent); d.age = 20; printf("%d \n", d.age); d.gender = 'F'; printf("%c \n", d.gender); return 0; } ``` **Output** ``` 38.22 20 F ``` ### Conceptual Memory View of Structures and Unions **Structure** ``` struct student { int age; char gender; loat percent; struct student s1; }; s1.age s1.gender s1.percent 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 9 bytes ``` **Union** ``` union student { int age; char gender; loat percent; union student s1; }; Memory Sharing (s1.age, s1.gender, s1.percent) 4000 4001 4002 4003 4 bytes ``` ### Difference Between Structure and Union | Feature | Structure | Union | |---|---|---| | Keyword | struct | union | | Memory Allocation | Allocated for each member | Allocated as per largest member | | Memory Sharing | No | Yes | | Element Value Modification | No effect on other members | Affects all other members | | Maximum Memory Allocation | Sum of member sizes | Size of largest member | | Member Access | All members can be accessed at a time | Only one member can be accessed at a time | | Storage Space | More | Less | | Initialization | All members can be initialized | Only the first member can be initialized | ### Program to Demonstrate the difference between Structure and Union ```c #include <stdio.h> #include <string.h> // Defining a structure to hold student details struct student_struct { char name[20]; int roll_no; float marks; }; // Defining a union to hold student details union student_union { char name[20]; int roll_no; float marks; }; void main() { // Creating and initializing a structure variable struct student_struct s; strcpy(s.name, "Srikanth"); s.roll_no = 101; s.marks = 92.0; // Creating and initializing a union variable union student_union u; strcpy(u.name, "Srikanth"); u.roll_no = 101; u.marks = 92.0; printf("\nSize of Structure: %lu bytes\n", sizeof(s)); printf("Size of Union: %lu bytes\n", sizeof(u)); printf("Structure Data: Name: %s, Roll No: %d, Marks: %.2f \n", s.name, s.roll_no, s.marks); printf("Union Data: Name: %s, Roll No: %d, Marks: %.2f\n", u.name, u.roll_no, u.marks); } ``` **Output** ``` Size of Structure: 28 bytes Size of Union: 20 bytes Structure Data: Name: Srikanth, Roll No: 101, Marks: 92.00 Union Data: Name: Roll No: 1119354880, Marks: 92.00 ```

Use Quizgecko on...
Browser
Browser