Thursday 23 February 2012

Structures in C and C++ programming


Structure :
A structure is a meaningful collection of data items of different types under a unique name.
Declaration of a structure

Struct name
{
Type1 data1;
Type2 data2;
.
.
.
Typen datan;
};


Where
Struct is a keyword
Name  is name of structure
Type1,. . . typen  are basic data type.
Data1, . .. datan is data items or structure variables.

Example

Struct stud
{
Int name[20];
Int branch[20];
Int semester;
};


Like ordinary variables, we can  also define and declare structure variables. The general form of declaring structure variables is
Structure_type varlist;
Example: struct stud x, y;
This can be done with the structure declaration.

Example

Struct stud
{
Int name[20];
Char branch[20];
Int semester;
} x, y;




Processing of a structure


Processing of a structure is mainly concerned  with accessing a structure member. Each member of a structure is accessed with a dot operator, that is the decimal point.to access a particular member, this dot operator must placed between the name of structureand the name of the structure member.
For example:
Stud.name
The result of expression is name of the student of type struct stud.the dot operator has highest priority thanany other operator in c,and associativity is left to right.
Embedded structure declaration

A structure within another structure is called embedded structure.
Example:

Struct employee
{
Int emp_code;
Char name[20];
Float salary;
Struct date
{
Int day;
Int month;
Int year;
}date_of_birth;
};


Initialization of a structure


Structure can be initialized as
Static struct stud student=(“kumar”, “ computer science”,8};
This will store kumar in name array computer science In branch array and 8 in semester aray.

Array of  structure
Whenever the same structure is to be applied to a group of people, items, etc.., in such situation , an array of structures will be definrd. In array of structures  each element is array in itself.
Example:
Struct stud_rec
{
Int rollno;
Char name[3];
Int m1;
Int m2;
Float avg;
}stud_rec[30];


This code will create an array of this structure in which there is record of student is stored.
Type definition, typedef statement
All variables are declared withthere basic datatype  such as int , float, char etc. it is possible for the user to define his/her own datatype  for the variables being used in program.c provides typedef  statement that enables the program to define an alternate term to the basic dattype. Once the typedef is made, the earliar datatype , all variables, arrays, structures etc, can be declared with the new data type.
Syntax:

Typedef old_ data_ type new_ data_ type;
Example
Struct stud_rec
{
Int reg_no;
Char name[25];
Char branch[20];
Int semester;
};


Typedef struct stud_rec learner;
Thus, we can declare any structure of type struct student in terms of learner.
Learner s1;

No comments:

Post a Comment