Module 7: Structures in C
Learning Objectives
1. To understand the concept of structure
2. To learn Declaration of structure
3. To learn Initialization of structure
4. To learn accessing structure members
Table of Content
1. Introduction
2. Basics of structure
3. Declaring structure variables
4. Structure Initialisation
5. Accessing structure members
6. Example program for structure
7. Uses of structure
8. Summary
1. Introduction:
C constants can be divided in to two major categories: Primary Constant, Secondary
Constant. Primary type of constant holds only single value or single character. Whereas
secondary types of constant holds multiple values or characters. The secondary constants are
array, structures, pointers, enumeration and union.
Structure is a user-defined data type in C which allows you to combine different data types to
store a particular type of record. Structure helps to construct a complex data type in more
meaningful way. It is somewhat similar to an Array. The only difference is that array is used
to store collection of similar data types while structure can store collection of any type of
data. Structure is used to represent a record. Suppose if it is required to store record
of Student which consists of student name, address, roll number and age then simple array
cannot store this information because here some fields are characters as well as numbers. In
short, data types are different. In such situation, a structure can be defined to hold this
information
Keyword struct is generally used whenever lot of data needs to be grouped together. For
example, it can be used to hold records from a database or to store information about
personal contacts in an address book. In the contacts, we can store name, address, phone
number, email etc.
In previous module, we have studied arrays. The array allows defining type of variables that
can hold several data items of the same kind. Similarly structure is another user defined data
type available in C that allows combining data items of different kinds, or we can say
structure is the collection of variables of different types under a single name for better
data handling.
2. Basics of structure
Structures are basically derived data types because they are constructed using objects of other
data types. C Structure is a collection of different data types which are grouped together and
each element in a C structure is called member. Basically Structure is used to store the
complicated data. A structure is a convenient way of grouping several pieces of related
information together.
One popular example of a structure is the students record. A college student is described by
a set of attributes such as name, address, roll number, class, division etc. Some of these in
turn could be structures: a name has several components, as does an address and even a roll
number.
A structure is a composition of multiple data types which may have same name. These
different data types are called as the fields or members of the structure. struct statement is
used to define a structure. The struct statement defines a new data type, with more than one
member. The format of the struct statement is as follows
Syntax of structure:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type member n;
};
The structure declaration starts with the keyword struct followed by the name of the
structure which defines its data type. It then has a pair { } which contains the
members of the structure. For example,
struct test
{
int x,
int y;
float z;
}
In this example, test is the name of structure which consist of two int and one float
type data together. Here x and y are members of type int and z is of type float.
Points to remember:
1. Keyword struct introduces the structure definition.
2. Sturct is followed by the structure tag, which names the structure definition
3. Structure tag is used to declare variables of the structure type.
4. Variables declared within braces of structure definition are the members of
structure.
5. Members of the same structure type must have unique names.
6. Members can be variables of primitive data types like int, float, char or other
data types like arrays, pointers etc.
7. Each structure definition must end with a semicolon.
3. Declaring Structure variable
A struct is a complex data declaration that defines a physically grouped list of variables to be
placed under one name in a block of memory, allowing the different variables to be accessed via
a single pointer or the struct declared name which returns the same address. There are
different ways to declare structure variable.
(a) Immediately after Structure Template
When a structure is define, it creates a user defined type but no storage is allocated for it.
Such structure for employee, variable can be declared as:
struct employ
{
int sal;
char name[40];
int age;
} employ;
//„employ' is name of Structure variable
(b) Declare Variable using struct Keyword
Another way to declare a variable using struct keyword is shown below:
struct date
{
int date;
char month[20];
int year;
};
struct date today;
where date is name of structure and today is name of variable.
(c) Declaring multiple structure variable
In many cases it is necessary to declare more than one structure variables. A simple method
to implement this is shown in the following example.
struct student
{
int roll no;
char name[20];
float markes;
} stud, stud2, stud3;
We can declare multiple variables separated by comma directly after closing curly bracket.
Another way to declare structure variables separately is shown below.
struct applicant
{
int srno;
char name[50];
int age;
} struct applicant a1, a2, a3;
Let us now learn methods for initializing the structure.
4. Structure Initialization:
Like any other data type, structure variable can also be initialized at compile time.
struct student
{
int roll_no;
char name[20];
float marks;
};
struct student stud1={23,Obaid,78.77}; //initialization
or,
/* initialization of each member separately */
struct student stud1;
Stud1.roll_no = 23;
Stud1.name = Obaid;
Stud1.markes = 78.77;
Note that if there are less initializers in the list than members in the structure, the remaining
members are automatically initialized to 0 or NULL.
In the next section, let us learn how to access the structure members.
5. Accessing Structure Members
Structure members can be accessed and assigned values in number of ways. Structure
member has no meaning independently. In order to assign a value to a structure member, the
member name must be linked with the structure variable using dot . operator. It is also
called period or member access operator. The structure member operator ``.'' connects the
structure name and the member name. One can also use scanf() to assign values to structure
member through keyboard. Another way of accessing structure members is structure pointer
operator (->) we will see in detail in the module related to pointers.
The syntax for accessing the member of a structure is
structure_variable_name.member_name
Suppose, it is necessary to find the age of any employee emp1 then it can be accessed as
emp1.age
Let us consider another example,
struct student
{
char name [20];
int rollno;
char addr[50];
}s1, s2;
s1.rollno=21;
//s1 is variable of student type and rollno is member of structure student.
We can also use scanf() to give values to structure members through terminal
scanf(" %s ", s1.name);
scanf(" %d ", &s1.rollno);
Array of structures:
Just like any other normal array, we can also declare an array of structure. Each array element
represents a structure variable. For example:
struct student stud[50];
This statement declares an array stud of size 50 elements. Each element of array stud is of
type students.
Just similar to int or float array, it is possible to read elements i.e. assign values to the
members, process or even print the values of an array elements.
In C language nesting of structure is also possible. For example:
struct student
{
char name[20];
int rollno;
struct addr
{
char area[20];
char city[20];
int pin;
};
};
6. Example program for c structure
This program is used to store and access “id, name and percentage for one student.
We can also store and access these data for many students using array of structures. You can
check C Array of Structures to know how to store and access these data for many
students.
#include <stdio.h>
#include <string.h>
struct student
{
int roll_no;
char name[20];
float percentage;
};
int main()
{
struct student record = {0};
//Initializing to null
record. roll_no =1;
strcpy(record.name, Obaid");
record.percentage = 77.15;
printf(" Roll number is: %d n", record.roll_no);
printf(" Name is: %s n", record.name);
printf(" Percentage is: %f n", record.percentage);
return 0;
}
Output:
Roll number is: 7
Name is: Obaid
Percentage is: 77.15
Example program for another way of declaring c structure:
In this program, structure variable “recordis declared while declaring structure itself.
In above structure example program, structure variable “struct student record is declared
inside main function which is after declaring structure.
#include <stdio.h>
#include <string.h>
struct student
{
int roll_no;
char name[20];
float percentage;
}record;
int main()
{
record. roll_no =1;
strcpy(record.name, Obaid");
record.percentage = 77.15;
printf(" Roll number is: %d n", record.roll_no);
printf(" Name is: %s n", record.name);
printf(" Percentage is: %f n", record.percentage);
return 0;
}
Output:
Roll number is: 7
Name is: Obaid
Percentage is: 77.15
C structure declaration in separate header file:
In above structure programs, C structure is declared in main source file. Instead of
declaring C structure in main source file, we can have this structure declaration in another file
called “header file and we can include that header file in main source file as shown below.
Header file name structure.h
Before compiling and executing below C program, create a file namedstructure.h” and
declare the below structure.
Header file where C structure is declared.
Program to Store Information of Single Variable
In this program, a structure(student) is created which contains name, roll and marks as
its data member. Then, a structure variable(s) is created. Then, data (name, roll and
marks) is taken from user and stored in data members of structure variable s. Finally,
the data entered by user is displayed.
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
struct student s;
printf("Enter information of students:\n\n");
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}
Output
Enter information of students:
Enter name: Adele
Enter roll number: 21
Enter marks: 334.5
Displaying Information
naume: Adele
Roll: 21
Marks: 334.50
7. Uses of c structures
1. C Structures can be used to store huge data. Structures act as a database.
2. C Structures can be used to send data to the printer.
3. C Structures can interact with keyboard and mouse to store the data.
4. C Structures can be used in drawing and floppy formatting.
5. C Structures can be used to clear output screen contents.
6. C Structures can be used to check computer‟s memory size etc.
8. Summary
Structure is a user-defined data type in C which allows you to combine different data
types to store a particular type of record. Structure helps to construct a complex data
type in more meaningful way.
Keyword struct is generally used whenever lot of data needs to be grouped together.
Sturct is followed by the structure tag, which names the structure definition
Structure tag is used to declare variables of the structure type.
Variables declared within braces of structure definition are the members of
structure.
Members of the same structure type must have unique names.
Members can be variables of primitive data types like int, float, char or other
data types like arrays, pointers etc.
Each structure definition must end with a semicolon.
The structure member operator ``.'' connects the structure name and the member
name. One can also use scanf() to assign values to structure member through
keyboard.
Just like any other normal array, we can also declare an array of structure. Each array
element represents a structure variable.
Just similar to int or float array, it is possible to read elements i.e. assign values to the
members, process or even print the values of an array elements.