To copy elements of one array to another array of same data type elements are copied one by one. It is not possible to copy elements at a time. Where as in structure it is possible to copy the contents of all structure elements of different data types to another structure var of its type using assignment (=) operator. It is possible because structure elements are stored in successive memory locations.
Nesting of structures is also possible.
‘struct’ keyword is used to define a structure, struct define a new data type which is a collection of different type of data.
struct structure_name
{
//Statements
};
struct Book
{
char name[15];
float price;
int pages;
};
Here the struct Book declares a structure to hold the details of book which consists of three data fields, namely name, price and pages. These fields are called structure elements or members. Each member can have different data type, like in this case, name is of char type and price is of float type etc. Book is the name of the structure and is called structure tag.
Like any other data type, structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or,
struct patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
There are two types of operators used for accessing members of a structure.
• Member operator (.)
• Structure pointer operator ()
Any member of a structure can be accessed as:
Syntax : structure_variable_name.member_name
Suppose, if we want to access age for variable p1. Then, it can be accessed as :
P1.age;
#include<stdio.h>
struct book
{
char book1 [30];
int pages;
float price;
};
main ( )
{
struct book bk1 = { “c++”, 300, 285};
printf (“ \n Book name : %s “ , bk1.book1);
printf (“\n No of pages :%d “,bk1.pages);
printf (“\n book price :%f “,bk1.price);
}
Book name: C ++
No of pages: 300
Book Price: 285