Site icon i2tutorials

Declaring Structure Variable

Declaring Structure Variable

 

After defining the structure, variables for that structure are to be declared to access the members of structures.

 

Syntax for declaration of structure variable :

 

struct structurename var1,var2,var3,……varn;

 

Example:

 

struct book b1, b2, b3;

 

The variables b1, b2, b3 are variables of the type struct book.

The memory is allocated for structures only after the declaration of the structure variable. The memory allocated is equal to the sum of memory required by all the members in structure definition.

 

Example:

 

struct book b1, b2, b3;

 

This statement assigns space in memory for b1,b2,b3. It allocates space to hold all the elements in the structure—in this case, 7 bytes—one for the name, four for the price, and two for pages. These bytes are always in adjacent memory locations.

 

Example:

 

struct student
{
char name [10];
int rno;
float marks;
} ;
struct student s1,s2;

 

The above declaration allocates 16 bytes(10 bytes for the name,2 bytes for roll number, and 4 bytes for marks) for s1 and 16 bytes for s2.

 

The variables for structure can be declared in three different ways:

 

method 1:

 

struct structure name
{
 datatype1 var1,var2,…;
 datatype2 var1,var2,…;
 ……………
 ……………
 datatypen var1,var2,…; };
 struct structurename var1,var2,var3,……varn;

 

method 2:

 

struct structure name
{
 datatype1 var1,var2,…;
 datatype2 var1,var2,…;
 …………….
 ……………
 datatypen var1,var2,…;
 }var1,var2,var3,…..varn;

 

method3:

 

struct
{
 datatype1 var1,var2,…;
 datatype2 var1,var2,…;
 …………….
 ……………
 datatypen var1,var2,…;
 }var1,var2,var3,…..varn;

 

Method 3 cannot be used for future declaration of variables as the structure tag is not present.

 

Note: The use of structure tag is optional in C language.

 

Variables for structure book are declared in 3 different ways:

 

Example 1:

 

struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, b3 ;

 

Example 2:

 

struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;

 

Example 3:

 

struct
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;

 

Accessing Members of Structure:

 

The members of the structure are accessed by the dot (.) operator.

 

The Syntax for accessing members of the structure are:

 

 Structure varname.member name;

 

So to refer to pages of the structure defined in our structure book example we have to use,

 

b1.pages

 

Similarly, to refer to the price we would use,

 

b1.price.

 

Exit mobile version