In Segment 263, you saw a program in which
memory for a single trade
object is allocated when the program is compiled.
The following alternative version demonstrates the use of a pointer
variable, the sizeof
function, malloc
function, and pointer
casting.
Note that no memory is allocated for any trade
object at compile time.
Instead, memory is allocated at compile time for a trade
pointer.
Then, at run time, memory for a single trade
object is allocated by the
malloc
function, and that memory is referenced via the
trade
pointer.
#includestruct trade {double price; int number;}; double trade_price (struct trade *t) {return t -> price * t -> number;} main ( ) { double price; int number; struct trade *tptr; tptr = (struct trade*) malloc (sizeof (struct trade)); while (2 == scanf ("%lf%i", &price, &number)) { tptr -> price = price; tptr -> number = number; printf ("The total value of the trade is %f.\n", trade_price (tptr)); } printf ("You seem to have finished.\n"); } --- Data --- 10.2 600 12.0 100 13.2 200 --- Result --- The total value of the trade is 6120.000000. The total value of the trade is 1200.000000. The total value of the trade is 2640.000000. You seem to have finished.
Note that the purpose of this version is to illustrate the run-time allocation concept; it has no memory-conserving advantage. In the hardcopy version of this book, you learn about a more complex program that does illustrate memory conservation.