![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
Now consider the following, revised version of the trade_price
function. Conspicuously, no value is returned. Equally conspicuously, a
second parameter appears, result
, a pointer to a floating-point
number:
*-- No value is returned *-- Extra parameter | | v v void trade_price (struct trade *tptr, double *result) { *result = tptr -> price * tptr -> number; }
Because result
is a pointer parameter, its value must be the address
of a chunk of memory allocated before trade_price
is called. The
assignment statement writes the product of the price
and
number
structure variables into that chunk of memory.
Thus, the computation performed in the trade_price
function is
passed out via the memory chunk identified by a dereferenced pointer,
rather than via a normal return value. Put to use, this version of the
trade_price
function appears in the following revised version of the
analyze_trades
program; note the introduction of the floating-point
variable, trade_price_result
, which provides the chunk of memory
that the result
pointer parameter identifies:
#include/* Define the trade structure */ struct trade {double price; int number;}; /* Define value-computing function */ void trade_price (struct trade *tptr, double *result) { *result = tptr -> price * tptr -> number; } /* Define trade array */ struct trade trades[100]; main ( ) { /* Declare various variables */ int limit, counter; double trade_price_result, sum = 0.0; /* Read numbers and stuff them into array */ for (limit = 0; 2 == scanf ("%lf%i", &trades[limit].price, &trades[limit].number); ++limit) ; /* Display value of shares traded */ for (counter = 0; counter < limit; ++counter) { trade_price (&trades[counter], &trade_price_result); sum = sum + trade_price_result; } printf ("The total value of the %i trades is %f.\n", limit, sum); } --- Data --- 10.2 600 12.0 100 13.2 200 --- Result --- The total value of the 3 trades is 9960.000000.