Structure declarations are a bit more complex than array declarations, since a structure must be defined in terms of its individual members.In general terms, the composition of a structure may be defined as
struct tag {
member 1;
member 2;
...............
member n;
};
In the above declaration struct is the required keyword; tag is the name of the structure; and member 1, member 2,......., member n are individual member declarations.(Note: there is no formal distinction between a structure definition and a structure declaration; the terms are used interchangeably.)
The member names must be distinct from one another within a particular structure, though a member name can be same as the name of a variable that is defined outside of the structure. A storage class, however cannot be assigned to an individual member, and individual members cannot be initialized within a structure type declaration.
Once the composition of the structure has been defined, individual structure-type variables can be declared as follows
storage-class struct tag variable 1,variable 2,............,variable n;
where storage-class is an optional storage class specifier, struct is a required keyword, tag is the name that appeared in the structure declaration, and variable 1,variable 2,............,variable n are structure variables of type tag.
It is possible to combine the declaration of the structure composition with that of the structure variables, as shown below.
storage-class struct tag {
member 1;
member 2;
...............
member n;
}variable 1,variable 2,............,variable n;
The tag is optional in this situation.
A C program contains the following structure declarations.
struct date {
int month;
int day;
int year;
};
struct account {
int acct_no;
char acct_type;
char name[80];
float balance;
struct date lastpayment;
} oldcustomer, newcustomer;
The second structure (account) now contains another structure (date) as one of its members.Note that declaration of date precedes the declaration of account. The following diagram explains the composition of account.
The assignment of initial values to the members of a structure variable are done as
static struct account customer = {12345, 'R', "John", 550.50, 5, 24, 90};
Thus, a customer is a static structure variable of type account, whose members are assigned initial values. The first member(acct_no) is assigned the integer value 12345,the second member(acct_type) is assigned the character 'R', the third member name[80] is assigned the string "John", and the fourth member(balance) is assigned the floating-point value 550.50. The last member is itself a structure that contains three integer members (month, day and year). Therefore, the last member of customer is assigned the integer values 5, 24 and 90.
Monday, April 19, 2010
Subscribe to:
Comments (Atom)