Programming and Graphics

(Kiana) #1

5.6 Pointers to free memory 145


The syntax of the function-pointer declaration is illustrated near the top of the
code. The main program calls the functionoperatewith a function-pointer
argument that requests division or multiplication. A sample session is:


Please enter 1 for the ratio and 2 for the product q to quit
1
4/2=2
2
4x2=8
q

Problem


5.5.1.Add to thepointerfuncode two more functions to perform addition and
subtraction.


5.6 Pointerstofreememory


We have discussed pointers associated with declared variables. It is possible to
introduce a pointer not associated with a declared variable but corresponding
instead to unused or free memory that is available to all programs.


When a new pointer is declared, the corresponding memory address is
reserved and the associated memory content is initialized to zero. If the new
pointer declaration fails because free memory is not available, the system will
throw an exception.


A pointer corresponding to an undeclared integer is introduced by the
statements:


int * pname;
pname = new int;

wherepnameis a chosen pointer name. The two statements can be consolidated
into one:


int * pname = new int;

A pointer corresponding to an undeclared real variable registered in double
precision is declared as:


double * somename = new double;

Similar declarations are made for different data types.

Free download pdf