Structure is user defined data type .It is tool by which we can store the data of different type like int ,float, char etc in single record. In array we can store only same type of data but structure encapsulates different data type variable in single record.
Syntax:
Struct [struct_type_name]
{
[type variable_name [,variable_name, …]];
[type variable_name [,variable_name, …]];
[type variable_name [,variable_name, …]];
………………………………………………….
………………………………………………….
} [structure_variable_name];
Example:
struct book
{
char *title;
int page;
int pub_year;
float price;
}book1,book2;
How to access the structure members?
Ans:
We can access the structure member with the help of . or -> operator.
First declare any structure variable:
struct book list;
Now to access any member variable write :
Structure.variable .member_variable
Example
list.title=”C programming”;
list.price=300.0;
If structure variable is pointer type then use ->
Example:
struct *list;
list->title=”C programming”;
list->price=300.0;
note : -> is similar to (*) . so you can write (*list).price=300.0;
Instead of writing srtuct book we can give a simple name by typedef keyword
e.g
typedef struct book BOOK;
BOOK *list;
list->page=400;
Or
(*list).page=400;
Member of structure are bounded to each other i.e if we sort only one member like year then automatically other member variable like title, price etc will sort.
Program:
void main()
{
int i,j;
struct book
{
char *title;
int page;
int pub_year;
float price;
};
struct book list[3],k;
//inserting the data
list[0].title="C programming";
list[0].page=300;
list[0].pub_year=1965;
list[0].price=410;
list[1].title="C coding";
list[1].page=270;
list[1].pub_year=1802;
list[1].price=200;
list[2].title="Advance c";
list[2].page=410;
list[2].pub_year=1993;
list[2].price=600;
//output before sorting
clrscr();
printf("TITLE\t\tPAGE\tPUB.\tPRICE\n\n");
for(i=0;i<3;i++)>//only sorting of page
for(i=0;i<3;i++) j="0;jlist[j+1].page)
{
k=list[j];
list[j]=list[j+1];
list[j+1]=k;
}
}
}
printf("After sorting of only page\n\n\n");
for(i=0;i<3;i++)>
Output:

