Structure in C – Part 2

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.

1

2

3

4

5

6

7

8

9

10

11

12

//structure definition

structstudent

{

charname[10];

introll;

intmarks;

}s1;

structstudent s1={"Rishi",4,56};//storing values

//accessing structure elements

printf("%s%d%d",s1.name,s1.roll,s1.marks);

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

#include<stdio.h>

intmain()

{

structlibrary

{

charlang[10];

intpages;

charname[20];

};

structlibrary lib[3];

inti;

for(i=0;i<3;i++)

{

printf("nEnter language, pages and namen");

scanf("%s%d%s",&lib[i].lang,&lib[i].pages,&lib[i].name);

}

for(i=0;i<3;i++)

printf("n%st%dt%sn",lib[i].lang,lib[i].pages,lib[i].name);

return0;

}

Output

Explanation
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.