Structure Variables:
A structure is a collection of data items or elements. It is defined to declare its variables. These are called structure variables. A variable of structure type represents the members of its structure.
When a structure type variable is declared, a space is reserved in the computer memory to hold all members of the structure. The memory occupied by a structure variable is equal to the sum of the memory occupied by each member of the structure.
A structure can be defined prior to or inside the main ( ) function. If it is defined inside the main ( ) function then the structure variables can be declared only inside the main function. If’ it is defined prior to the main ( ) function, its variables can be defined anywhere in the program. To declare a structure variable, the structure is first defined, e.g.
struct address
{
char city [15];
int pcode;
}
address taq, aye;
In the above example, city and pcode are the members of structure address. The variable taq and aye are declared as structure variables. The structure address has two members: city and pcode. The variable city occupies 15 bytes and pcode occupies 2 bytes. Thus each variable of this structure will occupy 17 bytes space in memory, i.e. 15 bytes for city and 2 bytes for pcodc.
Accessing Members of a Structure:
The dot operator (.) is used to access the members of a structure. To access a member of a specific structure, the structure variable name, the dot operator and then the member of the structure is written.
The syntax to access a member of a structure is:
struct_variable.struct_element
struct_variable It specifies the name of the structure variable. A period or full-stop specifies the dot operator.
struct_element It specifies the actual element of the structure whose value is to he accessed.
Program: Write a program to input data into and then print data from the members of a structure.
# include <iostream.h>
# include <conio.h>
struct address
{
char city [15];
int pcode;
main ( )
{
address taq;
clrscr ( );
cout << “Enter City ? ”;
cin >> taq.city;
cout << “Enter Postal Code ? ”;
cin >> taq.pcode;
cout << “Output from structure” << endl;
cout << “City:” << taq.city << endl;
cout << “Postal Code:” << taq.pcode << endl;
}
In the above program, a structure address is defined. A variable taq of this structure is declared. The data is entered into the members of the structure address with reference to structure variable taq. The dot operator is used between the structure variable taq and members of the structure.
comment closed