Pages

Thursday, June 27, 2013

INTRODUCTION TO STRUCTURES IN C++

A structure is a collection of different variable types grouped together.
You can refer to a structure as a single variable and to its parts as members of that 
variable by using the dot (.) operator.
For Example:
// struct1.cpp
struct PERSON { // Declare PERSON struct type
int age; // Declare member types
float weight;
char name[25];
}; 
int main() {
PERSON sister;
PERSON brother; // C++ style structure declaration
sister.age = 13; // assign values to members
brother.age = 7;
return 0;
}
Difference between Array and structures:
Although arrays greatly improved our ability to store data, there is one major drawback to 
their use ... each element (each box) in an array must be of the same data type.  It is 
often desirable to group data of different types and work with that grouped data as one 
entity.  We now have the power to accomplish this grouping with a new data type called 
a structure.
Struct initialization:
You can initialize a structure by:
1.  PERSON boy={20,65,”Ali”};   //age 20, weight 65, name Ali
// initializes are used when contiguous members may be given
2.  PERSON boy;
boy.age=20; boy.weight=65;

No comments:

Post a Comment