Structure in C – Part 2

By | February 10, 2015
Read: Structure in C – Part 1

In the last tutorial I told you about the basic use of structure in C programming. I gave an overview of declaration and definition of structures. Armed with that basic knowledge, today I will tell you about how to access structure elements. Apart from this I will also tell you about the memory allocation of structure elements and array of structure. So lets get started.

Structure in C

Accessing Elements of Structure

It is important to define the structure before accessing it. In arrays we use subscript to access the array elements. But this concept is slightly different from them. To access the structure elements we use dot operator or member access operator (.). We have to write the name of structure variable followed by a dot and structure element. One small example is given below.

Above code will display the name, roll number and marks of student s1. Consider carefully I have accessed the elements using dot operator.

Memory Allocation of Structure Elements

Structure elements are stored similar to array elements. It means the structure elements are also stored in contiguous memory locations. As I have said earlier, at the time of structure variable declaration, memory is allotted to it. In our above example 14 bytes (10 for string and 4 for two integers) will be allocated for s1.

Array of Structure

Before proceeding to this topic I want to ask you – Is it possible to create array of structure? Well of course Yes. If we can make array of pointers, array of chars and so on then we can also make array of structure.

Making an array of structure is similar to creating a normal array. For this we only need to define a structure. After that we have to make an array of structure. Consider below program to understand it properly.


Structure in C - Part 2

In this example I am storing the records of books in a library system. You can see I have created an array of structure of size 3 and that is storing 3 records from the user and then displaying the same on the screen.

Leave a Reply

Your email address will not be published. Required fields are marked *