Tuesday, January 5, 2010

9.5 PASSING STRUCTURES TO FUNCTIONS

There are many different ways to pass structure-type information to or from a function.Structure members can be transferred individually or the whole structure can be passed to a function.

Individual structure members can be passed to a function as arguments in the function call, a single structure member can be returned via the return statement.To do so, each structure member is treated the same as an ordinary single-valued variable.

Consider the simple C program shown below.

#include < stdio.h >

typedef struct  {
int acct_no;
char acct_type;
char *name;
float balance;
} record;

main()  /*transfer a structure-type pointer to a function*/

{
 void adjust(record *pt);   /*function declaration*/


static record customer = {"Smith", 5120, 'R', 100.35};


printf("%s  %d  %c   %.2f\n",customer.name, customer.acct_no, customer.acct_type, customer.balance); 

adjust(&customer); 

printf("%s  %d  %c   %.2f\n",customer.name, customer.acct_no, customer.acct_type, customer.balance);



}

void adjust (record *pt)     /*function definition*/
{
pt->name = "Jones";
pt->acct_no = 5635;

pt->acct_type = 'C';
pt->balance =200.65; 

return; 
}


This program illustrates the transfer of a structure to a function by passing the structure's address(a pointer) to the function.in particular, customer is a static structure of type record, whose members are assigned an initial set of values.These initial values are displayed when the program begins to execute.The structure's address is then passed to the function adjust, where different values are assigned to the members of the structure.


Execution of the program results in the following output.


Smith  5120  R  100.35
Jones  5635  C  200.65

Thus the values assigned to the members of  customer within adjust are recognized within main, as expected.

No comments:

Post a Comment