0% found this document useful (0 votes)
8 views28 pages

Structure and Union

Uploaded by

amansah97027
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views28 pages

Structure and Union

Uploaded by

amansah97027
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

STRUCTURE AND UNION

Compiled By: Ravi Singh


INTRODUCTION TO STRUCTURE
▪ A structure is a user defined data type. The syntax of structure declaration is
We know that arrays can be used to struct structure_name
represent a group of data items that
belong to the same type, such as int or {
float. type element 1;
▪ We cannot use an array if we want to type element 2;
represent a collection of data items of ……………..
different types using a single name.
type element n;
▪ A structure is a convenient tool for };
handling a group of logically related
data items. ▪ In structure declaration the keyword struct
appears first, this followed by structure name.
▪ Structure is a user defined data type ▪ The member of structure should be enclosed
used to represent a group of data items between a pair of braces and it defines one by
of different types using a single name. one each ending with a semicolon.
▪ It can also be array of structure. There is an
enclosing brace at the end of declaration and it
end with a semicolon
2
Compiled By: Ravi Singh
STRUCTURE DECLARATION
▪ We can declare structure variables as follows struct student
struct structure_name var1,var2,…..,var n;
{
▪ To store the names, roll number and total mark
of a student you can declare 3 variables. int rollno;
▪ To store this data for more than one student 3 char name[25];
separate arrays may be declared. float totalmark;
▪ Another choice is to make a structure. };
▪ No memory is allocated when a structure is We can now declare structure variables stud1,
declared. stud2 as follows
▪ It just defines the “form” of the structure. When
a variable is made then memory is allocated.
struct student stud1,stud2;
▪ This is equivalent to saying that there's no
memory for “int”, but when we declare an Thus, the stud1 and stud2 are structure variables
integer that is int var; only then memory is of type student. The above structure can hold
allocated. The structure for the above mentioned information of 2 students.
case will look like
3
Compiled By: Ravi Singh
ACCESSING STRUCTURE VARIABLE
▪ The different variable types stored in a structure are called its members.
▪ The structure member can be accessed by using a dot (.) operator, so the dot operator
is known as structure member operator.
Syntax
structure_variable.structure_member;
Example:
In the above example stud1 is a structure variable of type student. To access the
member name, we would write
stud1.name ;
Similarly, stud1’s rollno and stud1’s totalmark can be accessed by writing
stud1.rollno;
stud1.totalmark;
4
Compiled By: Ravi Singh
STRUCTURE DECLARATION
▪ It is possible to combine the declaration of ▪ The single declaration is equivalent to the two
structure combination with that of the structure declaration presented in the previous
variables, as shown below. example.
struct student
struct structure_name {
{ int rollno;
type element 1; char name[25];
type element 2; float totalmark;
…………….. } stud1, stud2;
type element n;
} var1,var2,…,varn;

5
Compiled By: Ravi Singh
INITIALIZING STRUCTURE MEMBERS
▪ Structure members can be initialized at declaration.
▪ This much the same manner as the element of an array; the initial value must appear in the
order in which they will be assigned to their corresponding structure members, enclosed in
braces and separated by commas.

The general form is


struct structure_name var={val1,val2,val3…..};

Example:

Compiled By: Ravi Singh 6


INITIALIZING STRUCTURE MEMBERS

Compiled By: Ravi Singh 7


STRUCTURE AS STRUCTURE MEMBER (NESTED STRUCTURE)
▪ A structure inside another structure is called an embedded structure or nested structure.
▪ A structure can have one or more of its member as another structure.
Syntax
struct Inner {
int innerValue;
float innerFloat;
};
struct Outer {
int outerValue;
struct Inner innerStruct; // Nested structure
};

Compiled By: Ravi Singh 8


EXAMPLE OF NESTED STRUCTURE

Compiled By: Ravi Singh


9
SIZE OF STRUCTURE
▪ The size of a structure is the total amount of memory ▪ What is padding?
required to store all of its members, including any
padding added for alignment purposes. ▪ Padding is extra space inserted by the compiler between
the members of a structure to ensure proper alignment of
▪ The size can be determined using the sizeof data in memory. This helps the CPU access data
operator. efficiently, as most CPUs are optimized for accessing data
that is aligned to certain Memory Address (byte offset) |
Example Content
#include <stdio.h> ▪ -----------------------------|-------------------------
▪ 0 | a (1 byte)
struct Example { ▪ 1 | Padding (1 byte)
char a; // 1 byte ▪ 2 | Padding (1 byte)
int b; // 4 bytes (typically) ▪ 3 | Padding (1 byte)
}; ▪ 4 | b (4 bytes)memory boundaries.

int main() { Output


printf("Size of struct Example: % bytes\n",
sizeof(struct Example));
return 0;
}
Compiled By: Ravi Singh 10
ARRAY OF STRUCTURE
▪ In C programming, the combination of arrays and structures i.e. array of structures provides a
powerful tool for managing that.
▪ An array whose elements are of type structure is called array of structure. It is generally useful
when we need multiple structure variables in our program.
Need for array of structure
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.

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


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

11
Compiled By: Ravi Singh
ARRAY OF STRUCTURE
▪ In C programming, the combination of arrays and structures i.e. array of structures provides a
powerful tool for managing that.
▪ An array whose elements are of type structure is called array of structure. It is generally useful
when we need multiple structure variables in our program.
Need for array of structure
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.

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


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

12
Compiled By: Ravi Singh
ARRAY OF STRUCTURE
Declaration
struct struct_name
{
type element 1;
type element 2;
……………..
type element n;
}array name[size];

Example

struct student
{
int rollno;
char name[25];
float totalmark;
} stud[100]; 13
Compiled By: Ravi Singh
STRUCTURE AND FUNCTION
▪ Like an ordinary variable, a structure
variable can also be passed to a function.
▪ We may either pass individual structure
elements or the entire structure.
Passing structure members to functions
▪ A structure member can be treated just as
any other variable of that type.
▪ For example, an integer member of structure
can be treated just as an integer.
▪ Thus, structure members can be passed to
function like ordinary variables.
▪ Example program to illustrate passing
structure members to a function :

14
Compiled By: Ravi Singh
STRUCTURE AND FUNCTION
Passing whole structure to a functions

▪ It is possible to send entire structures to


functions as argument in the function call.
▪ The structure variable is treated as any
ordinary variable.
▪ Example A program to illustrate passing
whole structure to function.

15
Compiled By: Ravi Singh
STRUCTURE AND FUNCTION
Passing array of structure to a function
It is possible to send entire array of structures
to functions as argument in the function call.

Example
A program to illustrate passing whole
structure to function.

16
Compiled By: Ravi Singh
POINTER TO STRUCTURE
Pointers can be used also with structure. To store address of a structure
type arable, we can define a structure type pointer variable as normal
way. Let us consider structure book that has members name, page and
price. It can be declared as
struct book
{
char name[10];
int page;
float price;
};
struct book b;

Then, we can define structure variable and pointer variable of structure


type. struct book b; /* b is structure variable */
Compiled By: Ravi Singh 17
POINTER TO STRUCTURE
▪ Here, b is simple variable of structure type book where bptr is pointer type variable which points or
can store address of structure book type variable.
▪ This declaration for a pointer to structure doesn't allocate any memory for a structure. It allocates only
for a pointer.
▪ To use structure's members through pointer bptr, memory must be allocated for a structure by using
function by adding declaration and assignment as given below.
bptr=&b;
▪ Here, the base address of b can assigned to bptr pointer.

▪ An individual structure member can be accessed in terms of its corresponding pointer variable by
writing
ptr_variable->member
▪ Here, -> is called arrow operator and there must be pointer to the structure on the left side of this
operator.
▪ i.e.Now, the members name, pages and price of book can be accessed as

b.name or bptr->name or (*bptr) .name or b.page or bptr->page or (*bptr).page b.price


or bptr->price or (*bptr).price Compiled By: Ravi Singh 18
POINTER TO STRUCTURE
▪ Here, b is simple variable of structure type book where bptr is pointer type variable which points or
can store address of structure book type variable.
▪ This declaration for a pointer to structure doesn't allocate any memory for a structure. It allocates only
for a pointer.
▪ To use structure's members through pointer bptr, memory must be allocated for a structure by using
function by adding declaration and assignment as given below.
bptr=&b;
▪ Here, the base address of b can assigned to bptr pointer.

▪ An individual structure member can be accessed in terms of its corresponding pointer variable by
writing
ptr_variable->member
▪ Here, -> is called arrow operator and there must be pointer to the structure on the left side of this
operator.
▪ i.e.Now, the members name, pages and price of book can be accessed as

b.name or bptr->name or (*bptr) .name or b.page or bptr->page or (*bptr).page b.price


or bptr->price or (*bptr).price Compiled By: Ravi Singh 19
EXAMPLE OF POINTER TO STRUCTURE
Create a structure named book which has
name, pages and price as member variables.
Read name of book, its page number and
price. Finally display these member’s value.
Use pointer to structure itself to access
member variables.

20
Compiled By: Ravi Singh
TYPEDEF
▪ In C programming, the typedef keyword is used to provide existing data types
with new names.
Creating an Alias for Data Types:
▪ You can use typedef to redefine the name of an existing data type. This is helpful
when the original type name becomes cumbersome or less intuitive.
▪ The syntax for typedef is:
typedef existing_name alias_name;
▪ After this declaration, you can use alias name as if it were the real existing_name
in your C program.

Compiled By: Ravi Singh 21


EXAMPLE: USING TYPEDEF WITH STRUCTURE

Compiled By: Ravi Singh 22


INTRODUCTION TO UNION
▪ 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.

▪ In above example, structure members a and b have different addresses where as union members a
and b have same addresses. It means the union members a and b are storing same memory
locations.
Compiled By: Ravi Singh 23
UNION DECLARATION
A union is declared in the same way as a For example, the following code declares a union
structure. The syntax of union declaration is data type called Student and a
union union_name union variable called stud:
{ union student
type element 1; {
type element 2; int rollno;
................. F loat totalmark;
type element n; };
}; union student stud;
This declares a type template. Variables are
then declared as:
union union_name x,y,z;

Compiled By: Ravi Singh 24


UNION DECLARATION
It is possible to combine the declaration of The following single declaration is equivalent to
union combination with that of the union the two declaration presented in the previous
example.
variables, as shown below.
union union_name
union student
{
{
type element 1;
int rollno;
type element 2;
float totalmark;
.................
}x,y,z;
type element n;
}var1,var2,...,varn;

Compiled By: Ravi Singh 25


EXAMPLE OF UNION
Create a union named student that has roll and To access both members of an union, we need it
marks as member. Assign some values to these to access each member one by one as shown
members one at a time below.
.

Compiled By: Ravi Singh 26


DIFFERENCE BETWEEN STRUCTURE AND UNION
Point of Difference Structure Union

Memory Allocation Allocates memory for all its Allocates memory only for the
members. largest member.

Total Size Sum of sizes of all members. Size of the largest member.

Data Storage Can store values for all members Can store value for only one
simultaneously. member at a time.
Use Case When you want to group different When you want to save memory
data types and access all of them at and only need one data type at a
once. time.
Example struct example { union example {
int a; int a;
float b; float b;
} }
Accessing Members All members can be accessed at any Only the last stored member can
time. be accessed.
Modification Impact Modifying a member doesn’t affect Modifying one member may
Compiled By: Ravi Singh 27
other members. overwrite other members.
Compiled By: Ravi Singh 28

You might also like