Pages

Friday, February 13, 2015

Structure in C Part 2

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.


//structure definition
struct student
{
char name[10];
int roll;
int marks;
}s1;

struct student 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.


#include<stdio.h>

int main()
{
struct library
{
char lang[10];
int pages;
char name[20];
};

struct library lib[3];
int i;

for(i=0;i<3;i++)
{
printf("
Enter language, pages and name
");
scanf("%s%d%s",&lib[i].lang,&lib[i].pages,&lib[i].name);
}

for(i=0;i<3;i++)
printf ( "
%s %d %s
",lib[i].lang,lib[i].pages,lib[i].name);

return 0;
}

Output

Structure in C - Part 2

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.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.