Introduction
Ordinary variables are able to hold one piece of information and arrays can hold different pieces of information of the same data type. But we often require entities that are collection of different data types. This is where the requirement for structure comes in.
In other words, structure, like a record, is a collection of one or more variables, usually of different types, grouped together under a single name. A structure lets us use this group as a unit instead of separate entities. For example, a bank account can contain the account number, name of the person, the address and bank balance as one entity.
Declaring a Structure
A structure declaration creates a format that may be used to declare structure variables. For example, suppose we want to store bank account information which includes account number (an unsigned integer), name of the person (a string), address (a string), and balance (a float). We can define a structure to hold this information as shown below:
struct account
{
unsigned int account_no;
char name[20];
char address[50];
float balance;
};
The keyword struct declares a structure to hold the details of four fields, viz. account number, name, address and balance. These individual fields are called structure elements or members. Each member may be of a different data type. Account is the name of the structure and is called the structure tag. The tag name may be used subsequently to declare variables that have the tag's structure.Note that the above declaration has not declared any variables and does not tell the compiler to reserve any space in memory.
in general, a structure can be declared as:
struct tag_name
{ data-type member 1;
data-type member 2; data-type member n;
};
Once the composition of the structure has been defined, the individual structure variables can be declared as follows:
storage-class struct tag_name variable*!, variable2, ..., variablen;
where storage class is an optional storage class specifier, struct is a required keyword, tag_name is the name of that appeared in an already declared structure type, and variable1, variable2, ..., variablen are structure variables of type tag_name.
For example, once we have declared the structure of type account, we can declare the structure variables customerl and customer2 as follows:
struct account customerl, customer2;
If we desire, we can combine the declaration of the structure type and structure variables as shown below:
struct tag_name
{ data-type member 1; data-type member 2;
data-type member n; } variable1, variable2, ..., variablen;
In this situation, the tag_name is optional.
For example, the customerl and customer2 could be declared by
struct account
{
unsigned int account_no;
char name[20];
char address[50];
float balance; } customer1, customer2;
or
struct
{
unsigned int account_no; char name[20];
char address[50]; float balance; } customerl, customer2;
Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined. In very large programs they are usually put in a separate header file, and the file is included, using the preprocessor directive #include, in whichever program we want to use this structure type.
Initializing a Structure
Like primary variables and arrays, structure variables can also be initialized where they are declared. The format is quite similar to that used to initialize arrays.
storage-class struct tag_name variable = {value1, value2, ..., valuen};
where value1 refers to the value of the first member, value2 refers to the value of the second member, and so on.
For example,
struct account customer = { 345621, "Tom", "Riverside, California", 95678.50};
It is also possible to initialize as shown below:
struct account
{
unsigned int account__no;
char name[20];
char address[50];
float balance; } customer = { 345621, "Tom", "Riverside, California", 95678.50};
C does not permit the initialization of individual structure members within the template. The initialization must be done only in the declaration of the actual variables.
Accessing Structure Elements
It is possible to access the individual members of a structure as separate entities. Structure elements can be accessed in two ways, viz. using the period operator and using the arrow operator. For now, let us understand how to I access structure elements using the period operator, we will learn about the arrow operator later in this chapter.
A structure member can be accessed by writing
variable.member
where variable refers to the name of a structure type variable, and member refers to the name of a member within the structure. The period(.) that
separates the variable name and member name is called the member operator; it is a member of the highest precedence group and its associativity is left-to-right.
For example, if customer is a structure variable of type account, then we can access the customer's account_no by writing
customer.account_no
Similarly, the members name and balance can be accessed by writing
customer.name and
customer.balance
Since the period or member operator is a member of the highest precedence group, this operator will take precedence over the unary operators as well as the different arithmetic, relational, logical and assignment operators.
For example,
++variable.member is equivalent to (variable.member)
that is, the ++ operator will apply to the structure member and not the structure variable.
Similarly, &variable.member is equivalent to &(variable.member)
that is, the expression accesses the address of the structure member and not the starting address of the structure variable.
Example:
struct account
{
unsigned int account_no;
char name[20]; char address[50]; float balance;
};
main()
{
struct account customer;
printf("Enter data for customer:\n");
scanf("%d %s %s %f", &customer.account_no, customer.name,
customer.address, &customer.balance);
printf("\nThe customer's name starts with %c\n",customer.name[0]); printf("The data entered for the customer :\n%d \n%s \n%s \n%.2f \n", customer.account_no, customer.name, customer.address,
customer.balance); }
Output:
Enter data for customer:
345621
Tom
Riverside, California
95678.5
The customer's name starts with T
The data entered for the customer:
345621
Tom
Riverside, California
95678.50
This example illustrates how structure elements can be accessed using the period or member operator. Note that the variable name with a period and member name is used like an ordinary variable. Thus, the ampersand^) precedes both account__no and balance, but does not precede name and address(since they are string variables). Also notice, how the first character of the customers name is accessed. This illustrates how the individual elements of an array within a structure can be accessed.
Array of Structures
We use structures to describe the format of a number of related variables. For example, in analyzing the customer information in a bank, we may use a template to describe customer information and then declare all the customers as structure variables. In such cases, we may declare an array of structures, each element representing a structure variable.
For example,
struct account customer[50];
defines an array called customer, that consists of 50 elements. Each element is defined to be of type struct account.
It is also possible to initialize the array where it is declared as shown below:
struct account customer[3] =
{{ 345621, "Tom", "Riverside, California", 95678.50}, {823720, "Dick", "Clear Lake, Texas", 89347}, { 873774, "Harry", "Baltimore, Maryland", 94583.50}};
This declares the customer array as an array of three elements customer[0], customer[1] and customer[2] and initializes their members as:
customer[0].account_no = 345621; customer[0].name = "Tom"; customerjoj.address = "Riverside, California"; customerjoj.balance = 95678.50; customer[1].account_no = 823720;
customer[2]. balance = 94583.50;
Note that the array is declared just as it would have with any other array. The use of the period operator can be extended to an array of structures by writing,
Array[expression].member
where array refers to the array name. Thus array [expression] is an individual array element (a structure variable) and hence array [expression].member will refer to a specific member within a particular structure.
Nested Structures
A structure can be nested within another structure as one of the members. Consider the following definitions of two structures tagged address and account respectively in the following example:
Example:
struct address
{
char street[30]; charcity[16]; char state[16]; int pin;
};
struct account
{
unsigned int acc_no;
char name[20];
/* addr is a member of the struct account and of the type struct address */
struct address addr;
float balance;
};
If the following declarations are made,
struct address add; struct account customer;
then, the following are all valid member references:
add.pin
customer.acc_no customer.addr customer.addr.street
Note that an innermost member in a structure can be accessed by chaining all the concerned structure variables (from outer-most to inner-most) with the member using the dot operator.
The following program accepts today's date and displays it with tomorrow's date.
Example:
/* Program to determine tomorrow's date 7
#include
{
struct date
{
int month; int year; int day;
};
struct date today, tomorrow;
static int days_per_month [12] = {31,28,31,30,31,30,31,31,30,31,30,31};
printf ("Enter today's date (mm dd yyyy):\n");
scant ("%d%d%d", &today.month,&today.day,&today.year);
if (today.day != days_per_month[today.month -1])
{
tomorrow.day = today.day + 1;
tomorrow.month = today.month;
tomorrow.year = today.year;
>
else
if (today.month == 12)
{
tomorrow.day = 1; tomorrow.month = 1; tomorrow.year = today.year +1;
} else
{
tomorrow.day = 1;
tomorrow, month = today, month+1;
tomorrow.year = today.year;
} printf ("Tomorrow's date is %d/%d/%d\n",tomorrow. day, tomorrow, month.tomorrow. year);
} Output:
Enter today's date (mm dd yyyy):
7 16 1990
Tomorrow's date is 17/7/1990.
Exercise
Modify the above example to accept today's date and display it with yesterday's date.
Structures and Functions
Like an ordinary variable, a structure variable can also be passed to a function. There are three methods by which the values of a structure can be transferred from one function to another.
The first method is to pass individual structure elements as actual arguments of the function call. The actual arguments are then treated independently like ordinary variables.
Example:
main()
{
struct account
{
unsigned int account_no;
char name[20];
char address[50];
float balance;
};
struct account cust = { 345621, "Tom", "Riverside, California", 95678.50};
display(cust.account_no, cust.name, cust.address, cust.balance); }
display(ac_no, name, addr, bal) unsigned int ac_no; char 'name, *addr; float bal;
{
printf("\n%d \n%s \n%s \n%f \n", ac_no, name, addr, bal);
}
Output:
345621
Tom
Riverside, California
95678.50
Note that in the structure declaration, name and address have been declared as arrays. Therefore, when the function display is called using
display(cust.account_no, cust.name, cust.address, cust.balance);
the base addresses of the arrays name and address are passed, but the values stored in account_no and balance are passed.
It can be easily realized that, this method of passing individual structure elements, becomes unmanageable and inefficient when the structure size is large.
The second method involves passing a copy of the entire structure to the called function.
Example:
struct account
{
unsigned int aocount_no; char name[20]; char address[5C]; float balance;
};
Main()
{
struct account customer = { 345621, "Tom", "Riverside, California", 95678.50};
display(customer); }
display(cust) struct account cust
{
printf("\n%d \n%s \n%s \n%f \n", cust.account_no, cust.name, cust.address,
cust.balance);
}
Output:
345621
Tom
Riverside, California
95678.50
Note that here the calling of the function display becomes quite compact, display (customer);
However, there is another important difference between the above two programs. Notice that in the second example, the template of account is defined before main. This has made the data type struct account as global and has enabled the function display to make use of this definition.
The problem with this method is that since only a copy of the structure is passed and the function works on the copy, any changes made to the structure members within the function are not reflected in the original structure (in the calling function). It is, thus, necessary for the function to return the entire structure back to the original structure. Here notice the contrast with arrays, which cannot be returned via the return statement.
The third method passes as argument a pointer to the structure. In this case, the location address of the structure is passed to the called function. The function can thus indirectly access the entire structure and work on it. This method is more efficient than compared to the previous ones. Before going into details of this method, we should learn how to process structures using pointers. We will discuss the third method after we learn how to process structures using pointers.
Pointers
The way we can have a pointer pointing to an int, or a pointer pointing to a char, similarly we can have a pointer pointing to a struct. Such pointers are known as structure pointers.
The starting address of a structure can be accessed in the same manner as any other address, through the use of the address operator(&). Thus, if a variable represents a structure-type variable, then &variable represents the starting address of that structure variable. Moreover, we can declare a structure pointer by writing
type *ptr;
where, type is a data type that identifies the composition of the structure and ptr represents the name of the pointer variable.
We can then assign the starting address of a structure variable to this pointer by writing,
ptr = &variable;
Example:
struct account
{
unsigned int account_no; char name[20]; char address[50]; float balance;
};
struct account customer, *ptr;
In this example, customer is a structure variable of type account, and ptr is a pointer variable whose object is a structure variable of type account. The same thing can be achieved alternatively by writing,
struct account
{
unsigned int account_no;
char name[20J;
char address[50];
float balance; } customer, *ptr;
Once the structure variable customer and the pointer variable ptr for that structure type has been declared, we can assign the starting address of customer to ptr by writing, ptr = &customer;
An individual structure member can be accessed in terms of its corresponding structure variable by writing,
ptr->member
where, ptr refers to a structure-type pointer variable, and the symbol '->'(made up of a minus sign and a greater than sign) is called the arrow operator. Thus this expression is equivalent to
variable.member
where variable is a structure-type variable.
Like the period(.) operator, the arrow(->) operator also falls into the highest precedence group and its associativity is left-to-right.
The arrow operator can be combined with the period operator to access a submember within a structure by writing,
ptr->member.submember
Similarly, the arrow operator can be used to access an element of an array that is member of a structure, by writing,
ptr->member[expression]
Example:
main()
{
struct address
{
char street[30]; charcity[16]; char state[16]; int pin;
};
struct account
{
unsigned int account_no;
char name[20];
struct address addr;
float balance;
};
struct account cust = { 345621, "Tom", "Grand Canyon", "Riverside", "California", 987066, 95678.50}; struct account *ptr=&cust;
printf("Account No : %d\n", cust.account_no); printf("Account No : %d\n", ptr->account_no); printf("Account No : %d\n", (*ptr).account_no);
printf("\nState: %s\n", cust.addr.state); printf("State : %s\n", ptr->addr.state); printf("State : %s\n", (*ptr).addr.state);
printf("\nName starts with : %c\n", cust.name[0]); printf("Name starts with : %c\n", ptr->name[0]); printf("Name starts with : %c\n", (*ptr).name[0]); }
Output:
Account No : 345621 Account No : 345621 Account No : 345621
State : California State : California State : California
Name starts with : T Name starts with : T Name starts with : T
This example illustrates the processing of a structure using a structure pointer. Notice that the pointer variable ptr is initialized by assigning to it the starting address of the structure variable cust. The first three printf statements indicate that the expressions
cust.account_no, ptr->account_no, (*ptr).account_no
are equivalent. The parentheses are required in the last expression, because the period operator has a higher precedence than the indirection operator(*). Without the parentheses, the compiler would generate an error, because ptr is not directly compatible with the dot operator.
Similarly, the next three printf statements indicate that the expressions
cust.addr.state, ptr->addr.state, (*ptr).addr.state,
are equivalent.
Similarly, the last three printf statements indicate that the expressions
cust.name[0], ptr->name[0], (*ptr).name[0]
are equivalent.
Now let us extend the usage of the arrow operator to arrays of structures. We know that the name of an array stands for the address of its zero-th element. The same is true for the names of arrays of structure variables.
Example:
struct account
{
unsigned int account_no; char name[20]; char address[50];
float balance; } customer[3], *ptr;
This statement declares customer as an array of three elements, each of type struct account, and ptr as a pointer to objects of type struct account.
We can then assign the starting address of customer to ptr by writing,
ptr = customer;
Note that, the address(&) operator is not used, since the array name automatically gives the starting address. Thus ptr will now point to customer[0]. Its members can be accessed by writing,
ptr->account_no ptr->name ptr->address ptr->balance
or writing,
(*ptr).account_no (*ptr).name (*ptr).address (*ptr). balance
Similarly, when the pointer ptr is incremented by one, it is made to point to the next record i.e. customer[1].
Example:
struct account
{
unsigned int account_no;
char name[20]; char address[50]; float balance;
};
main()
{
struct account customer[100], *ptr;
for (ptr=customer; ptr
Printf(“Enter data :\n");
scanf("%d %s %[A\n] %f, &ptr->account_no, ptr->name,
ptr->address, &ptr->balance);
}
for(i=0;i<100;i++)
{
printf("\nThe data entered :\n");
printf("%d \n%s \n%s \n%.2f \n", ptr->account__no, ptr->name,
ptr->address, ptr->balance);
} }
This example illustrates the use of a structure pointer to manipulate the elements of an array of structures. Note that the pointer ptr is used as the loop control index in the for loops.
While using the structure pointers, we should take care of the precedence of operators. The operators '->', '.', () and [ ] have the highest priority among the operators.
Example:
#include
{
unsigned int account_no;
char name[20];
char address[50];
float balance;
};
Example:
struct account
{
unsigned int account_no; char name[20]; char address[50]; float balance;
};
main() {
struct account customer[100]; int i;
for(i=0;i<100;i++)
{ printf("Enter data for customer %d:\n",i);
scanf("%d %s %s %f", &customer[i].account_no, customer[i].name,
customer[i].address, &customer[i].balance);
} for(i=0;i<100;i++)
{
printf("\nThe customer's name starts with %c\n",customer[i].name[0]);
printf("\nThe data entered for the customer %d :\n%d \n%s \n%s \n%.2f \n", i, customer[i].account_no, customenTj.name, customer[i].address, customer[i].balance); }
}
This example is an enhancement of the example which illustrates how structure elements can be accessed using only a single structure variable. Notice that the program essentially remains the same, the only difference being the use of array subscripts.
marks student!, student2;
The declarations define marks as a 5-element, floating-point array type. Hence, student1 and student2 are 5-element, floating-point arrays.
The two statements typedef float marks[5]; marks student1, student2;
are equivalent to the following two statement
float student1[5]; float student2[5];
Another way to accomplish this is,
typedef float marks;
marks student1 [5], student2[5];
The typedef feature is particularly convenient when defining structures, since it eliminates the need of repeatedly writing struct tag_name, whenever a structure is referenced.
In general terms, a user-defined structure type can be written as
typedef struct {
data-type member1 ; data-type member2;
data-type membern; } new_type;
where new_type is the user-defined structure type. Structure variables can then be defined in terms of the new data type.
Example:
typedef struct
{
unsigned int account_no;
char name[20];
char address[50];
float balance; } record;
record customerl, customer2, bank[100];
The first declaration defines record as a user-defined data type. The second declaration defines customerl and customer2 as structure variables of type record, and an array bank whose elements are structure variables of type record.
The typedef feature can also be used repeatedly, to define one data type in terms of other user-defined data types.
Example:
typedef struct
{
char street[30J;
char city[16]; charstate[16]; int pin; } address;
typedef struct
{
unsigned int acc_no;
char name[20];
address addr;
float balance;
} record;
record bank[100];
In this example, address and record are user-defined structure types, and bank is a 100-element array, whose elements are structures of type record. The elements of the array and the structure members are accessed as before.
Self-referential Structures
A structure which contains a pointer to itself is called a self-referential structure. Let us see this through an example.
Example:
struct node
{
char letter;
int count;
struct node *next_ptr;
};
These are used in making linked lists, trees etc.
For applications using such data structures, Dynamic memory allocation
required which we will discuss in a later chapter.
Exercises
1. Write a program to accept 3 command line arguments and print them inthe reverse order.
Example : a.out one two three
The answer would be : three two one .
2. Write a program to accept the name , age and salary of 10 employees inan array of structures. Sort this array on the field name and display it on
the terminal.
3. Write the same program using pointer instead of an array.
4. Write a program using a structure to describe a motel. The structure should include the name of the motel, it's classification according to category (ordinary, deluxe, super deluxe), average room charge per day and the number of rooms in the motel.
Now write functions to perform the following tasks:
a) Print out motels of a given category in order of charges.
b) Print out motels with room charges les than a given value.
5. Define a structure called football that will describe the followinginformation:
Name of a player Name of the team Average number of goals scored by the player
Using football, declare an array called player with 30 elements and write a program to read the information about all the 30 players and print a team-wise list containing names of players with the average number of goals scored by them.
Unions
Unions, like structures, are derived datatypes, which group together a number of variables. However, the way the two treat these variables is entirely different. All the members of a union share the same memory area within the computer's memory, whereas each member within a structure is assigned its own unique area. Thus, unions are used to conserve memory. They are useful for applications with multiple members, where values need not be assigned to all of the members simultaneously.
A union is thus a variable that may hold (at different times) objects of different types and sizes, with the compiler keeping track of size and alignment requirements. It is, however, the programmer's responsibility to keep track of which type is currently stored in a union; an attempt to access the wrong type of information will produce meaningless results.
In general terms, the composition of a union may be defined as
union tag_name
{
data-type member1;
data-type member2;
data-type membern; }
where union is a required keyword and member"!, member2, membern are individual members.
Once the composition or template is defined, individual union variables can then be declared as
storage-class union tag_name variable11 variable2, ..., variablen;
where storage-class is an optional storage-class specifier, union is a required keyword, tag_name is the name that appeared in the union definition, and variable1, variable2, variablen are union variables of type tag_name.
As with structures, here also, the two definitions can be combined. Thus, we can write
storage-class union tag_name
{
data-type member1; data-type member2;
data-type membern;} variable1, variable2....... variablen;
The tag_name is optional in this type of declaration.
Example:
union id
{
int code;
char desc[12]; } item;
This statement declares a union variable item of type id. The variable item will be large enough to hold the largest of the union members: a block of memory large enough for the 12-character string(desc) will be j allocated to item. The compiler will automatically distinguish between' 12-character array (desc) and the integer quantity (code) within the giv block of memory, as required. The variable item can thus represent) either a 12-character string (desc) or an integer quantity (code) at one time; the type retrieved must be the type most recently stored. A note that, a union may only be initialized with a value of the type ol first member, thus the union variable item can only be initialized with an! integer value.
An individual union member can be accessed in the same manner as i individual structure member, using the operator'.'.
Example:
#include
main()
int utype;
typedef struct
{
int length;
int breadth;
} rectangle;
typedef struct
{
int a;
intb;
intc; } triangle;
typedef int circle;
union figure
{
rectangle rect; triangle tri; circle cir;
}fig;
printf("Enter type of figure (1 .rectangle 2.triangle 3.circle):"); scanf("%d", &utype);
switch(utype)
{
case 1 : printf("Enter length and breadth : ");
scanf("%d %d", &fig.rect.length, &fig.rect.breadth);
break; case 2 : printf(“Enter length of the sides :");
scanf("%d %d %d", &fig.tri.a, &fig.tri.b, &fig.tri.c);
break; case 3 : printf("Enter radius :");
scanf("%d", &fig.cir);
break;
}
switch(utype)
{ case 1 : printf(“Perimeter of the rectangle : %d\n",
2*(fig.rect.length+fig.rect.breadth));
break;
case 2 : printf("Perimeter of the triangle : %d\n", fig.tri.a+fig.tri.b+fig.tri.c); break;
case 3 : printf("Circumference of the circle : %f\n", 2*3.14*fig.cir); break;
case 4 : printf("lnvalid figure!"); } }
This example illustrates a typical application of a union variable and its manipulation. If the concepts of structures are clear, the declarations should be easy to follow. The variable utype is used to keep track of the current type stored in the jnion variable fig and the switch statement is used to process the variable accordingly. The remaining code is straightforward.
Enumerated Data Type
The use of this datatype is essentially to make piograms more readable. It allows the creation of our own datatype with predefined values.
In general terms, an enumeration may be defined as
enum tag_name {value-!, value2, ..., valuen};
where enum is a required keyword, tag_name is a name that identifies enumerations having this composition. Though its form is like a structure, the values mentioned within its braces do not indicate variables, but in fact are constant values that the enum can take.
Once the enumeration has been defined, corresponding enumeration variables can be declared as
storage-class enum tag_name variable"), vanable2, ..., variablen;
where storage-class is an optional storage class specifier, enum is a required keyword, tag_name is the name that appeared in the enumeration definition, and variable1, variable2, ..., variablen are enumeration variables of type tag_name.
As before, the enumeration definition can be combined with variable declarations as shown below.
storage-class enum tag_name {value1, value2............. valuen} variable1,
variable2...... variablen;
The tag_name is optional.
Railway reservations would do well to have an enum or enumerated data type of the following form:
Example:
enum rail {firstclass, secondclass, ac};
enum rail passenger1, passenger2;
Here firstclass, secondclass and ac are called enumerators, which are the values that the variable of the type enum rail can take. The next statement declares that passengerl and passenger2 are variables of the type enum rail. These variables cannot take values other than firstclass, secondclass and ac. Internally, these values can are treated as integers by the compiler. Hence, firstclass is interpreted as value 0, secondclass is treated as value 1 and ac as value 2. We can override these values by writing,
enum rail {firstclass=20, secondclass, ac=40};
those constants that are net assigned explicit values will automatically be assigned values which increase successively by 1 from the last explicit statement. This may cause two or more enumeration constants to have the same value. Thus in the above statement, firstciass is interpreted as value 20, secondclass is treated as value 21 and ac as value 40.
Enumeration variables can be processed in the same manner as other integer variables; that is, they can be assigned new values, compared and so on. It should however, be understood that enumeration variables are used internally, to indicate various conditions that can arise within a program. Hence, there are certain restrictions associated with their use. In particular, an enumeration constant cannot be read into the computer and assigned to an enumeration variable. Moreover, only the integer value of an enumeration can be written out of the computer.
Example:
enum colors { black, blue, green, red, white, yellow}; colors foreground, background;
if (background==black)
foreground=white; else
foreground=yellow;
if (foreground==background)
foreground=(enum colors) (foregoround+1);
This simple example illustrates various important concepts of enumerated variables.
It should be understood that enumeration variables do not provide any fundamentally new capabilities and that ordinary integer variables can always be used in place of enumeration variables. However, enumeration variables within a program can often increase the logical clarity of the program.
No comments:
Post a Comment