Chapter - 7structure and Union
Chapter - 7structure and Union
continue
Chapter -7
Structures & Unions
*What is a structure?
**Definition:
“It is defined as a collection of data
items of different data types grouped
together under a single name”.
Defining &Declaration:
Each and every structure must be
defined and declared before it appears
in a C-program.
*Syntax of structure definition
In the above syntax struct is a key word.
structurename is a name of the structure. It is also
known as tagname.
Type1, type2 …. Type n are the basic data types.
Member1, member 2 ----member n are the
members or fields of the structures. They are also
known as member variables.
{ it indicates starting of the structure.
} it indicates end of the structure.
The body of the structure is terminated by a
semicolon.
Ex: struct student
{
char sname[20];
int rollno;
float fee;
};
Declaration of variables inside the structure:
Accessing structure members through
variables
The link between members and variables is
established by using member operator or period
operator that is dot operator.
Eg:
struct student
{
int rollno;
float fee;
char sname[20];
}student1,student2 ;
We are accessing rollno of first student.
student1. rollno
We are accessing fees of second student
student2.fee
*typedef
typedef is a C keyword implemented to tell the
compiler to assign alternative names to C's pre-
existing data types. .
Syntax
typedef <existing_name> <alias_name>
In the above syntax, 'existing_name' is the name of
an already existing datatype while 'alias name' is
another name given to the existing variable.
Eg: typedef int hello;
hello a,b;
*UNION
Union
“It is a collection of heterogeneous elements of different
data types. This is similar to the structures”.
The main difference between the structures
and
union is that in structure each member
variable is assigned with its own memory
location, due to this sometimes memory will
be wasted. But in union all members share a
common memory location, due to this memory
is saved.
Declaration:
Syntax:
union unionname
{
type1 data1;
type2 data2;
:
type n data n;
};
In the above syntax union is a key word.
unionname is a name of the union. It is also known as tagname.
Type1, type2 …. Type n are the basic data types.
Data1, data2 ----data n are the members or fields of the union.
{ it indicates starting of the union.
} it indicates end of the union.
The body of the union is terminated by a semicolon.
Ex:
Ex: union student
{
int rollno;
float fee;
char sname[20];
};
Accessing
union members through variables
The link between members and variables is established
by using member operator or period operator that is
dot operator and also arrow operator ,this is
known as this operator.
Syntax:
unionvariable.unionmember
Dot operator
Ex:
union student
{
int rollno;
float fee;
char sname[20];
}s1,s2 ;
We are accessing rollno through first student.
s1. rollno or s1rollno
**Difference between union and structures