Lesson 8: Structures.
Prev || Home || Next
We have seen that arrays can be used to represent a group of data items that belong to the same type. However if we want to represent a collection of data items of different types using a single name, then we cannot use an array. C supports a structured data type known as structure, which is amethod for packing data items of different types. A structure is a convinient tool for handling a group of logically related data items. For example, it can be used to represent a set of attributes, such as student_name, roll_number & marks. The concept of a structure is analogous to that of a record in many other languages.
Consider a book database consisting of bookname, author, numberofpages & price. We can define a structure to hold this info as follows:
The keywoard struct declares a structure to hold the details of four fields namely, title, author, pages and price. These fields are called structure elements or members. Each member may belong to a different type of data, book_bank is the name of the structure & is called the structure tag. The tag name may be used subsequently to declare variables that have the tag's structure.
Now we can declare structure variables using the tag name anywhere in the program.
For example the statement
struct book_bank book1,book2,book3;
declares book1, book2 & book3 as variables of type struct book_bank. Remember that the members of a structure themselves are not variables. They do not occupy any memory until they are associated with the structure variables such as book1. It is also allowed to combine both structure declaration and variable declaration in one statement as below:
struct book_bank struct
char title; char title;
char author; char author;
int pages; int pages;
float price; float price;
Here no tag name is defined. Hence it cannot be used later in the program to define variables.
Program: Defining and assigning values to structure members.
struct personal person;
printf("\n Enter values");
Arrays of structure:
We can use structures to input a number of records. But if the number of records are more, the program will become too lengthy. Then we can define an array of structure as below
defines an array called student that consists of 100 elements. Each element is defined to be of the type struct class.
Program: Program with use of arrays of structures.
struct class student;
printf("\nEnter the roll_no,name and marks of the student");
Arrays within Structures:
C permits the use of arrays as structure members. We have already used arrays of characters inside structure. Similarly, we can use single or multi-dimensional arrays of type int or float.
For ex. the following structure declaration is valid
Here the member subject contsains three elements, subject, subject, subject. The name student.subject would refer to the marks obtained in the third subject by second student.
Prev || Home || Next