0% found this document useful (0 votes)
2 views

Module 5

This document covers the concepts of structures and unions in C programming, detailing their definitions, declarations, and uses. It explains how to manage complex data types through structures, including nested structures and arrays of structures, as well as the differences between structures and unions. Additionally, it provides examples of initializing and accessing structure members, and discusses the use of typedef for improved code readability.

Uploaded by

tusharsurti6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module 5

This document covers the concepts of structures and unions in C programming, detailing their definitions, declarations, and uses. It explains how to manage complex data types through structures, including nested structures and arrays of structures, as well as the differences between structures and unions. Additionally, it provides examples of initializing and accessing structure members, and discusses the use of typedef for improved code readability.

Uploaded by

tusharsurti6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

‘C’ Programming

Module 5
By Asst. Prof. Sudeshna Baliarsingh
Information & Technology Dept.
KJSIT, Mumbai
Structure and Union

● Concept of Structure and Union


● Declaration and Initialization of structure and union
● Nested structures
● Array of Structures
● Passing structure to functions
Entity
A single unique object in the real world that is being mastered. Examples of an
entity are a single person, single product, or single organization.

Entity type
A person, organization, object type, or concept about which information is
stored. Describes the type of the information that is being mastered. An entity
type typically corresponds to one or several related tables in database.

Attribute
A characteristic or trait of an entity type that describes the entity, for example,
the Person entity type has the Date of Birth attribute.
Why use structure?

In C, there are cases where we need to store multiple attributes of an entity. It is not
necessary that an entity has all the information of one type only.

It can have different attributes of different data types.

For example, an entity Student may have its name (string), roll number (int), marks
(float). To store such type of information regarding an entity student, we have the
following approaches:

● Construct individual arrays for storing names, roll numbers, and marks.

● Use a special data structure to store the collection of different data types.

So structure is a user defined datatype where there is collection of different data


types under a single name.
Structures are a fundamental tool in programming that help you organize, manage, and
manipulate data effectively. They are especially useful in larger programs where
managing complex data becomes crucial.
We use struct to group several related things in one place.
Definition of Structure

Before you can create structure variables, you need to define its data type. To define a struct, the struct
keyword is used.The struct define a new data type which is collection of different type of data.
C Structure Definition

Here, a derived type struct Person is defined.

Now, you can create variables of this type.

When a struct type is defined, no storage or memory is allocated.


To allocate memory of a given structure type and work with it, we need to create variables and
declare it.
Declaring Structure Variable separately

here “person1”,”person2”,p[20] are


the variable of type person

In both cases,

person1 and person2 are struct


Person variables
p[ ] is a struct Person array of size
20. And here memory is allocated.

Declaring Structure Variable with Structure definition


Note: here 'person1',
“person2”,”p[20]” are
structure variables of type,
Person. Struct person is
the datatype here
Create struct Variables: example 2

Method 1 Method 2
Memory allocation in structure:
Access Members of a Structure
There are two types of operators used for accessing members of a structure.

. - Member operator

-> - Structure pointer operator (will be discussed in the pointer section)


Suppose, you want to access the salary of person2. Here's how you can do it.
Examples
1. struct student 2. struct xyz
{ {
int rollno; int x; 1st invalid (assigning
float marks=60.5; float y; variable not allowed)
char name[20]; char x [10]; 2nd invalid (missing
char address[50]; } semicolon and same
};
variable name x)
3rd invalid (missing
semicolon )
3. struct abc 4. struct emp 4th valid
{ {
int x; char *empname;
int y; int empid;
Int z; };
}
In this example, we
define a structure
Point with two integer
members: x and y.
Then, we declare and
initialize three
structure variables
(p1, p2, and p3) using
the same structure
definition.
Initialize Structure Members
Initialization using Assignment Operator
You can initialize structure members individually using the assignment operator (=) after declaring the structure
variable.

Coordinates of p1: (5, 10)

In this example, we declare a


structure variable p1 of type Point
and then initialize its x and y
members individually using the
assignment operator.
Initialization using Initializer List
You can also initialize structure members using an initializer list when declaring the structure variable.

Coordinates of p1: (5,


10)

In this case, we declare


and initialize p1 in a single
step, providing values
for its x and y members
within curly braces.
Initialization using Designated Initializer List
Designated initializers allow you to specify the member you want to initialize explicitly. This is especially
useful when you want to initialize only specific members of a structure.

Coordinates of p1: (5, 10)

In this example, we use


designated initializers
(.x and .y) to specify
which members we
want to initialize. This
method is particularly
useful when you have
structures with many
members, and you
only want to initialize
a few of them.
What About Strings in Structures?
Strings can be stored in structures in C, but it's
important to understand how to work with them, as C
does not have a built-in string data type like some
other languages. Instead, C typically uses character
arrays to represent strings.

Storing Strings in Structures


To store strings in structures, you can use
character arrays as members of the
structure.

In this example, we define a structure


Person with a name member as a character
array and an age member as an integer. We
use the strcpy function from the string.h
library to copy the name "John Doe" into the
name member of person1.
In C, you cannot
directly assign a
string to an array
using the
assignment operator
(=). You need to use
the strcpy() function
to copy the string
into the array.
Simpler Syntax for Initializing Structures
You can use a simpler syntax to initialize structures at the time of declaration:

struct Person person1 = {"Alice Smith", 25};

This initializes person1 with the name "Alice Smith" and age 25 directly during declaration.

Copying Structures
You can copy the contents of one structure to another by using the assignment operator =:

struct Person person1 = {"Alice Smith", 25};


struct Person person2;
person2 = person1; // Copy contents of person1 to person2

This copies the values of person1 (name and age) into person2.

Modifying Values in Structures


You can modify values in a structure just like any other variable:

person2.age = 30; // Update age for person2


Arrays of structures
Need for Array of Structures
Suppose we have 50 employees and we need to store the data of 50 employees. So for that,
we need to define 50 variables of struct Employee type and store the data within that.
However, declaring and handling the 50 variables is not an easy task. Let’s imagine a bigger
scenario, like 1000 employees.

So, if we declare the variable this way, it’s not possible to handle this.

struct Employee emp1, emp2, emp3, .. . ... . .. ... emp1000;

For that, we can define an array whose data type will be struct Employee soo that will be
easily manageable.

struct Employee emp[];


WAP that manages a contact list using structures to store information about each contact, including their
name and phone number:
Explanation:
The above C program defines a structure named Contact to represent a
contact with two members: name and phoneNumber, each of which is an
array of characters. The program then defines an array contacts of type
Contact with a size of 3, which can hold information for up to 3 contacts.

In the main() function, the program populates the contacts array with
contact information by using the strcpy() function to copy strings into the
name and phoneNumber members of each contact.

After populating the contact list, the program iterates over the contacts array
using a for loop and prints out the information for each contact using printf().
It prints the name and phone number for each contact, separating each
contact's information with a newline character.
Write a program to read Title, author and price of 10 books using an array of
structure and Display the record.
wAP IN C ApplYING structure to display employee id
NAME AND WEEK ATTENDANCE
Output
Nested Structure in C
A Basic Example:
Ways in Which a Structure Can Be Nested

1. By Embedded Structure

As the name suggests, this method is used to embed one structure inside
another, i.e defining one structure in the definition of another structure.
Thus using this method, the nested structure will be declared inside
the parent structure.

2. By Separate Structure

The two structures are created separately in this method. The Dependent
structure is used inside the Main/Parent structure by taking a member
of the dependent structure type in the definition of the parent
structure.
Embedded structure follows Example
the below format:

In the above example, the


structure incomeInLPA has
been embedded within
structure employee. Thus
parent structure 'employee'
has three variables name,
employeeid and inc. The
further variable inc contains
base_salary, CTC, and
bonus. The structure
incomeInLPA is defined
inside the parent structure
employee.
Initializing Nested Structures

Nested Structures in C can be initialized at the time of declaration. There are two methods by
which we can initialize nested structures:

Method 1 : The embed structure is initialized first using the structure variable of that
structure, then the parent structure is initialized next using that already initialized member of
the embed structure.
In this program, employee is
our parent structure and
incomeInLPA is our
nested/embed structure.

We initialize our nested


structure first and create
the structure variable inc.

This structure variable is then


used for initializing the parent
structure employee variable
emp.
By Separate Structure
The two structures are created separately in this method. The Dependent structure is used inside the
Main/Parent structure by taking a member of the dependent structure type in the definition of the parent structure.
Method 2 Initialisation: Both the parent structure as well as nested structure are initialized
together.

As seen in the above


program, the incomeInLPA
structure hasn't been
initialized separately.
"Mike", and 92 will be
stored as name and
employeid in the employee
structure. {13, 27 ,13} will
be stored as base-salary,
ctc and bonus in
incomeInLPA structure
variable and these all three
variables are a member of
emp which is of type
employee.
Here are two structures defined:
Address and Employee.
The Employee structure contains
an instance of the Address
structure (empAddress) as a
member, making it a nested
structure.
In the main function, an instance
of the Employee structure (emp1)
is declared and initialized with
sample data.
The program then prints out the
employee's name, age, and
address by accessing the nested
structure members.
Passing Structure to Function
Normally if we write a program to print point coordinates using function then:
Passing Structure to Function
Pass the structure variable
separately.
We can pass the individual
members of the structure to the
function separately as
arguments.
Passing Structure to Function
Pass the structure variable at
once.
We can pass the individual
members of the structure to the
function at once.
Passing Structure to Function

Pass the structure Pass the nested


members separately structure variable
at once.

Pass the nested


structure variable at
once.
Passing Structure to Function
Explanation:
Pass the
We start by including the necessary structure
header Pass the nested
file stdio.h which provides input/output functionalities.
members separately structure variable
at once.
We define a structure named student using the struct keyword. This structure has three members: name, roll, and
marks.

We define a function named display which takes a pointer to a struct student as its argument. This function will
display the details of a student.

Inside the display function, we use printf to print the name of the student. We access the name member of the
student structure using the arrow operator (->) since student_obj is a pointer to a structure.Similarly, we print the
roll number of the student by accessing the roll member of the structure pointed to by student_obj.

Finally, we print the marks of the student by accessing the marks member of the structure pointed to by
student_obj.In the main function, we declare an instance of the student structure named st1 and initialize it with
the values "Aman" for name, 19 for roll, and 8.5 for marks.

We call the display function, passing the address of the st1 structure as an argument. This means we're passing a
reference to st1, allowing the display function to directly access and modify the original structure.
C typedef
The typedef is a keyword that is used to provide existing data types with a new
name. The C typedef keyword is used to redefine the name of already existing data
types.

When names of datatypes become difficult to use in programs, typedef is used with
user-defined datatypes, which behave similarly to defining an alias for commands.

It can be used with structures to increase code readability and we don’t have to type
struct repeatedly.
Example : Using typedef to define a name for a structure
Output
Name: Kamlesh Joshi
Branch: Computer
Science And
Engineering
ID_no: 108
C Unions
The Union is a user-defined data type in C language that can contain elements of the different
data types just like structure. But unlike structures, all the members in the C union are stored
in the same memory location. Due to this, only one member can store data at the given
instance.

The syntax to declare a union is with the union keyword, similar to the way struct is used for
structures.

Syntax
This implies that although a
union may contain many
members of different types,
it cannot handle all the
members at the same time.
C Union Declaration

A union is defined using the union keyword. For instance:

The declaration here includes a


union named "circle" with two
members, name and radius. At the
same time, two union variables
circle1 and circle2 are created.

This declares a variable circle1 and circle2 of type union circle. This union contains two
members each with a different data type. However only one of them can be used at a
time. This is due to the fact that only one location is allocated for all the union variables,
irrespective of their size. The compiler allocates the storage that is large enough to hold
the largest variable type in the union.
Different Ways to Define a Union Variable
When you declare a union, you can simultaneously define union variables:

In the example here, stud1 and stud2 are union


variables declared alongside the student union

Defining Union Variable after Declaration

Here, the union variables stud1 and stud2 are


defined after the student union declaration.
Accessing Union Members

To access the members of a union, you use the dot (.) operator. If you have a pointer to a union, then you'd use the
arrow (->) operator.
Example of Union
A real-world example is a
two-wheeler dealership that
has both bicycles and
motorcycles. While a
motorcycle might have
attributes like engine size
and mileage, a bicycle might
only have attributes like color.
However, both might have a
price attribute. Using unions,
the memory space for these
attributes can be optimized:
Discuss the
implementation of a
structure with a union in
C programming.

Consider the provided


records structure, which
includes a union
containing information
about motorcycles and
bicycles.
Describe how the
structure is defined, how
unions work within it, and
provide an example of
how to use and
manipulate instances of
this structure."

You might also like