Home Segments Index Top Previous Next

373: Mainline

Now it is time to develop a program that uses an array of pointers to structure objects. The program is to be a modification of the following program that reads trade prices per share and numbers of shares, stuffs them into an array of trade objects, and displays their total trade price:

#include   
/* Define the trade structure */ 
struct trade {double price; int number;}; 
/* Define value-computing function */ 
double trade_price (struct trade *tptr) { 
  return tptr -> price * tptr -> number; 
} 
/* Define trade array */ 
struct trade trades[100]; 
main ( ) { 
  /* Declare various variables */ 
  int limit, counter, number; 
  double price, sum = 0.0; 
  /* Read numbers and stuff them into array */ 
  for (limit = 0; 
       2 == scanf ("%lf%i", &price, &number); 
       ++limit) { 
    trades[limit].price = price; 
    trades[limit].number = number; 
  } 
  /* Display value of shares traded */ 
  for (counter = 0; counter < limit; ++counter) 
    sum = sum + trade_price(&trades[counter]); 
  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. 

The modified program does the same work, but differs in that memory is allocated for the pointers at compile time, leaving memory for the trade objects to be allocated at run time.