Pages

Friday, December 28, 2012

Declaring Structure Variables-C Programming


We can declare structure variable in two ways-
       1. With structure definition.
       2. Using the structure tag name.


1. With structure definition.

struct student {
char name[20];
int rollno;
float marks;
}stu1,stu2,stu3;


Here stu1,stu2,stu3 are variables of type struct student.When we declare a variable while defining structure template ,the  tagname is optional So we can declare them as -
struct {
char name[20];
int rollno;
float marks;
}stu1,stu2,stu3;

If we declare variable in this way, then we will not be able to declare other variables of this structure type anywhere else in the program nor can we send these structure variable to functions. It need arises to declare  a  variable of this type in the program the we will to write the whole template again.So tagname is optional but it is always better to specify a tagname for the structure.

2 . Using structure tagname

We can declare structure variable using structure tagname. This can be written as -
struct student {
char name[20];
int rollno;
float marks;
};
struct student stu1,stu2;
struct student stu3;
Here stu1,stu2 and stu3 are structure variables that are declared using the structure tag student. Declaring a structure variable reserves space in memory. Each structure variable declared to be of type struct student has three members viz. name,rollno,marks.The compiler will reserve space for each variable sufficient to hold all the members. For example each structure variable will occupy 26 bytes.(char =20,int =2,float=4)

Note :: Size of data types depend on compiler. Do not confuse 

No comments:

Post a Comment