Structure is a
collection of one or more variable types. As we know, the elements in an array
must be the same data type, and you must refer to the entire array by its name.
Each element (called a member) in a structure can be a different data type.
Structures have ability to group data of different data types together but work
with that data as a whole. Suppose a company has inventory system so item name
will be character array, quantity in stock will be integer and retail price
will be in double, so to deal with such system we will use structure.
To define a structure, we must use the struct statement. Struct
defines for your program a new data type with more than one member. The format
of the struct statement is
struct
{
Member definition;
Member definition;
Member definition;
.
.
.
} [one or more structure variables]
|
Each member definition is a
normal variable definition, such as int
i; or float sales[20]; or any other valid variable definition, including
structure pointers if the structure requires a pointer as a member. At the end
of the structure’s definition and before the final semicolon, you can specify
one or more structure variables. Here is how you declare the CD structure:
struct cd_collection
{
char title [ 25 ]; char artist [ 20 ]; int num_songs;
float price;
char date_bought [ 8 ];
} cd_collection cd1, cd2, cd3;
|
There are five members in above structure: two character
arrays, an integer, a floating-point value and a character array. The member
names are title, artist, num_songs, price and date_bought. To access member of
structure use the following syntax as:
cd1.price, cd2.price etc
Initialization
of structure’s member can also be possible when you declare a structure
such as:
struct cd_collection
{ char title [ 25 ]; char artist [ 20 ]; int
num_songs;
float price;
char date_bought [ 8 ];
} cd_collection cd1 =
{
“Red Moon Men”,
“Sam and the
sneeds”,
12,
200.50,
11/10/14”
};
|
To store data of 100 books one must require to use 100
different structure variables from book1
to book100, which is not very convenient. A better approach would be to use
an array of structure.
Comments
Post a Comment
if you have any confusion then ask hear.