Wednesday, November 2, 2011

Declaring a Structure in C programming language

In our example program, the following statement declares the structure type:
 
struct book
{
char name ;
float price ;
int pages ;
} ;

This statement defines a new data type called struct book. Each variable of this data type will consist of a character variable called name, a float variable called price and an integer variable called pages. The general form of a structure declaration statement is given below:
 
struct <structure name>
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
} ;

Once the new structure data type has been defined one or more variables can be declared to be of that type. For example the variables b1, b2, b3 can be declared to be of the type struct book, as,
struct book b1, b2, b3 ;
This statement sets aside space in memory. It makes available space to hold all the elements in the structure—in this case, 7 bytes—one for name, four for price and two for pages. These bytes are always in adjacent memory locations.
If we so desire, we can combine the declaration of the structure type and the structure variables in one statement.
 
For example,
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, b3 ;
is same as...
struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;
or even...
struct
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;

Like primary variables and arrays, structure variables can also be initialized where they are declared. The format used is quite similar to that used to initiate arrays.
 
struct book
{
char name[10] ;
float price ;
int pages ;
} ;

struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;

Note the following points while declaring a structure type:
(a) The closing brace in the structure type declaration must be followed by a semicolon.
(b) It is important to understand that a structure type declaration does not tell the compiler to reserve any space in memory. All a structure declaration does is, it defines the ‘form’ of the structure.
(c) Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined. In very large programs they are usually put in a separate header file, and the file is included (using the preprocessor directive #include) in whichever program we want to use this structure type
.

No comments:

Post a Comment