Unions and Structs
-
Create a new folder give it the name
unionsandstructs -
Create a new file called
unionsandstructs.cinside that folder -
modify the contents to look like this:
Exercise 1: Structs
Objective: Understand the concept of structs and their usage in C.
-
Create a C program that defines a
Personstructwith the following attributes:name(string)age(integer)height(float)
-
Write a function
printPersonthat takes aPersonstructas a parameter and prints its attributes. -
In the main function, create an instance of the
Personstruct,populate its attributes with your name, age and height, and use theprintPersonfunction to display the details. -
Suppressed Code... [30 lines]
#include <stdio.h> /** * @struct Person * @brief Represents information about a person. */ struct Person { char name[50]; ///< Name of the person. int age; ///< Age of the person. float height; ///< Height of the person. }; /** * @brief Prints details of a person. * @param p The person to be printed. */ void printPerson(struct Person p) { printf("Name: %s\nAge: %d\nHeight: %.2f\n", p.name, p.age, p.height); } /** * @brief Main function where the program starts execution. */ int main() { // Create an instance of Person, initialize its attributes, and print details struct Person person1 = {"Your Name", 1, 4.0}; printPerson(person1); return 0; }
Exercise 2: Unions
Objective: Explore the concept of unions and their applications in C.
-
Create a C program that defines a
Dataunionwith the following members:integerData(integer)floatData(float)charData(character)
-
Write a function printData that takes a
Dataunionas a parameter and prints the value based on the type of data (integer, float, or character). -
In the main function, create an instance of the
Dataunion, assign values to different members, and use theprintDatafunction to display the values. -
Suppressed Code... [33 lines]
#include <stdio.h> /** * @union Data * @brief Represents different types of data (integer, float, char). */ union Data { int integerData; ///< Integer data. float floatData; ///< Float data. }; /** * @brief Prints details of data, detecting its type. * @param d The data to be printed. */ void printData(union Data d) { printf("Data: "); printf("%d (Integer)\n", d.integerData); printf("%f (Float)\n", d.floatData); } /** * @brief Main function where the program starts execution. */ int main() { // Create an instance of Data, assign values, and print details union Data data1; data1.floatData = 123.45f; printData(data1); return 0; }
Exercise 3: Unions Vs Structs
In this exercise we are going to explore the difference between and struct and a union:
-
Create a
structcalledPersonwith the following attributes:- name (char size 50)
- age (integer)
- height (float)
-
Create a
unioncalledDatawith the following attributes:- integerData (Int)
- floatData (float)
- CharData (char)
-
In
maindefine a thestruct Personaspersonand theunion Dataasdata -
Reproduce the following code to assign
person.ageanddata.integerDataanddata.floatData:... // Accessing struct members person.age = 25; printf("Struct Member - Age: %d\n", person.age); // Accessing union members data.integerData = 42; printf("Union Member - Integer Data: %d\n", data.integerData); // Modify union member and access another member data.floatData = 3.14; printf("Union Member - Float Data: %.2f\n", data.floatData); -
Now we are going to compare the size of the
structand theunion, reproduce the following after lastprintf(...)line: Suppressed Code... [49 lines]
#include <stdio.h> /** * @struct Person * @brief Represents personal information about a person. */ struct Person { char name[50]; ///< Name of the person. int age; ///< Age of the person. float height; ///< Height of the person. }; /** * @union Data * @brief Represents different types of data (integer, float, char). */ union Data { int integerData; ///< Integer data. float floatData; ///< Float data. char charData; ///< Character data. }; /** * @brief Main function where the program starts execution. * @return 0 on successful execution. */ int main() { // Create an instance of the struct and union struct Person person; union Data data; // Accessing struct members person.age = 25; printf("Struct Member - Age: %d\n", person.age); // Accessing union members data.integerData = 42; printf("Union Member - Integer Data: %d\n", data.integerData); // Modify union member and access another member data.floatData = 3.14; printf("Union Member - Float Data: %.2f\n", data.floatData); // Demonstrate the size difference between struct and union printf("Size of Struct (Person): %lu bytes\n", sizeof(struct Person)); printf("Size of Union (Data): %llu bytes\n", sizeof(union Data)); return 0; }-
A
struct Personis defined with attributes representing personal information. -
A
union Datais defined with three members:integerData,floatData, andcharData. -
In the
mainfunction, an instance of both thestructand theunionis created. -
The program demonstrates how to access and modify members of the
structand theunion. -
It prints the size of the
structandunionto highlight the memory usage difference. -
This exercise illustrates the key differences between
structsandunions: -
Struct: Each member has its own memory space, and the size of thestructis the sum of the sizes of its members. -
Union: All members share the same memory space, and the size of theunionis determined by the largest member.
-
Exercise 4: Combining Structs and Unions
Objective: Understand how structs and unions can be combined for more complex data structures.
-
Create a new
structnamedEmployeewith the following attributes:personalInfo(a Person struct)jobInfo(a Data union representing various job-related information)
-
Write a function
printEmployeethat takes anEmployeestructas a parameter and prints both personal and job-related information using the previously defined functions (printPersonandprintData). -
In the main function, create an instance of the
Employeestruct, populate its attributes, and use theprintEmployeefunction to display the details. -
Suppressed Code... [76 lines]
#include <stdio.h> /** * @struct Person * @brief Represents information about a person. */ struct Person { char name[50]; ///< Name of the person. int age; ///< Age of the person. float height; ///< Height of the person. }; /** * @union Data * @brief Represents different types of data (integer, float, char). */ union Data { int integerData; ///< Integer data. float floatData; ///< Float data. char charData; ///< Character data. }; /** * @struct Employee * @brief Represents information about an employee. */ struct Employee { struct Person personalInfo; ///< Personal information of the employee. union Data jobInfo; ///< Job-related information of the employee. }; /** * @brief Prints details of data, detecting its type. * @param d The data to be printed. */ void printData(union Data d) { printf("Data: "); if (d.integerData) { printf("%d (Integer)\n", d.integerData); } else if (d.floatData) { printf("%.2f (Float)\n", d.floatData); } else { printf("%c (Character)\n", d.charData); } } /** * @brief Prints details of a person. * @param p The person to be printed. */ void printPerson(struct Person p) { printf("Name: %s\nAge: %d\nHeight: %.2f\n", p.name, p.age, p.height); } /** * @brief Prints details of an employee. * @param e The employee to be printed. */ void printEmployee(struct Employee e) { printf("Personal Information:\n"); printPerson(e.personalInfo); printf("\nJob Information:\n"); printData(e.jobInfo); } /** * @brief Main function where the program starts execution. */ int main() { // Create an instance of Employee, assign values, and print details struct Employee employee1 = {{"Alice", 30, 5.5}, {0}}; employee1.jobInfo.floatData = 75000.50; printEmployee(employee1); return 0; }
Additional Challenges:
Modify the Person struct to include an array of hobbies. Update the relevant functions and demonstrate the changes in the main function.
Extend the Data union to include an array of integers. Modify the printData function to handle this new data type.
Conclusion:
This lab covers the basics of using structs and unions in C. It helps in understanding how to define, initialise, and manipulate data using these fundamental concepts. Additionally, provides key knowledge and skills for the assignment.