A structure is a collection of
variables usually of different types that can be used as a single item to
handle data more efficiently. An array can be used only to represent a group of
data items that belong to the same type. But, if we want to represent a collection
of data items of different types using a single name, array can not be used. At
that situation, structure is used.
Defining a Structure:
Syntax:
struct
structure_name
{
type1 member_variable1;
type2 member_variable2;
.
.
typen member_variablen;
};
Once structure_name is declared as
new data type, then variables can be declared as
struct structure_name structure_variable;
An example:
Let us create a structure named
student that has name, roll, marks and remarks as members.
struct student
{
char name[20];
int roll;
float marks;
char remarks;
};
Here, student is structure name and
its members are name, roll, marks and remarks.Then different variables of type struct
student can be declared as
struct student st;
Here, struct student is new data
type and st is variable of that type. The multiple variables are declared as
struct student st1, st2,
st2;
Each variable has its own copy of
member variables. The member variables are accessed using dot (.) operator. For
example, st1.name is member variable, name, of st1 structure variable and
st2.name is the member variable, name, of second structure variable st2.
Similarly, st1.roll is the member, roll, of first structure variable st1 and
st2.roll is the member, roll, of second structure variable st2.
The structure definition and variable declaration can be combined as
following
struct student
{
char name[20];
int roll;
float marks;
char remarks;
}st1,st2;
or
struct
{
char name[20];
int roll;
float marks;
char remarks;
}st1,st2;
Comments
Post a Comment