Information Technology Reference
In-Depth Information
The
heun
function is like a subroutine in Fortran, i.e., it does not return any value,
which in C
CC
is indicated by declaring the return type as
void
.The
f
argument
is used to transfer the right-hand side of the ODE to this function (see page
222
for
details). For our test program, the following
f1
function will be supplied as the
f
argument to the
heun
function:
double f1 (double u) { return -u; }
Plain Arrays in C
CC
The argument
u
in the
heun
function is a basic C
CC
(or C) one-dimensional array,
with one index starting at 0. The array argument is declared as
double u[]
or
double
*
u
. The latter notation actually declares a pointer to a double, i.e., the mem-
ory address of a double. Arrays and pointers in C and C
CC
are very closely related;
array variables are represented by pointers to (i.e. the address of) the first array ele-
ment in memory. Indexing arrays is done with square brackets:
u[0]
,
u[1]
,and
so on. The array length (here
n+1
) must be transferred as a separate argument, as in
Fortran 77. Another similarity with Fortran is that there is no built-in check of the
validity of the array indices. Indexing arrays beyond their bounds is one of the most
common errors in these programming languages.
Arrays in C and C
CC
can be created at run time with an appropriate length after
some input data are read.
13
The syntax is as follows:
double
*
u = new double[n+1];
The
new
operator allocates a chunk of memory of sufficient size for storing
n+1
double-precision real numbers and returns a pointer to the first array element. We
can assign the returned pointer to a pointer variable
u
and index the array as
u[i]
.
When there is no further use for the array, it must be deallocated (deleted from
memory) by the syntax
delete [] u;
For every
new
there should a corresponding
delete
action. Issuing a
delete
twice
is a common error, and the result is just strange program behavior and abort mes-
sages such as
segmentation fault
. Matching all the
new
and
delete
statements
correctly appears to be one of the greatest challenges when developing C and C
CC
code.
Array Objects
Fortunately, C
CC
has safer array variables. The class
valarray
in the standard
C
CC
library offers a vector type (array with a single index). Here is a declaration
of an array
u
of length
n+1
, where each array element is a
double
:
13
Recall that Fortran arrays are declared with a fixed size at compile time.