Declaring a Structure
A Structure can be defined in C by the keyword struct followed by its name and a body enclosed in curly braces. The body of the structure contains the definitions of its members must have a name.
The declaration of end by a semicolon. The general form of structure declaration in C is given below. It is also called as a structure template.
struct<name>
{
member 1
member 2
:
member n
} ;
where struct is the keyboard, <name> is the name of the structure and is optional, member 1,2, …n are the individual member declaration.
Free Hand-Written Notes
Let us now define the c structure to describe the information about the student given in fig.
struct student
{
char name[20];
int age;
int roll;
char class[5];
};
The declaration means that the student is a type which is a structure consisting of data member: name, age, roll, and class.
Since student is a type in itself, some variables will have to be declared of this type before data can be stored into the structure variable.
Therefore a variable s1 of type student can be declared as given below:-
Once this declaration is done, we get a variable s1 of type student in the computer memory which can be visualized as shown in fig.
Memory Space allocated to variable s1 of type student
A programmer is allowed to declare one or more structure variables along with the structure declaration as shown below: –
struct student
{
char name[20];
int age;
int roll;
char class[5];
};
s1,s2;
In this declaration, the Structure declaration and the variable declaration of the Structure type have been clubbed i.e. Structure declaration is followed by two variable names s1 and s2 and the semicolon.
Accessing Structures Elements
The Structure variable s1 has four members; name, age, roll and class. These members can be designated as: s1.name, s1.age, s1.roll, and s1.class respectively.
In this notation, an individual member of the Structure is designated by the Structure variable followed by a period and the member name. The period is called as Structure member operator or dot operator.
Thus the information of a student fig. can be stored in Structure variables s1 in the following manner.
s1.name = "Pawanpreet";
s1.age = 21;
s1.roll = 1251;
s1.class = "BSC";
If needed, the variable s1 can be read or written in C program by the input/output statements as shown below: –
gets(s1.name);
scanf("%d%d%s", &s1.age, &s1.roll, s1.class);
printf("%s%d%d%s", s1.name, s1.age, s1.roll, s1.class);