\documentstyle[12pt]{article}
\oddsidemargin 0.25in
\topmargin -0.5in
\textheight 8.5in
\textwidth 6.25in
\newcommand{\doublespace}{
   \renewcommand{\baselinestretch}{1.5}
   \large\normalsize}
\newcommand{\singlespace}{
   \renewcommand{\baselinestretch}{1.0}
   \large\normalsize}
\newcommand{\be}{\begin{equation}}
\newcommand{\ee}{\end{equation}}

\input epsf
\begin{document}
\setcounter{page}{13}

\centerline{\large{\bf LECTURE 2}}

\centerline{\bf Pointers}

A pointer contains an address in memory of a variable.
\begin{verbatim}
   int i = 2;
   int *p;	      // p is a pointer to an int
   p = &i;            // p stores the address of i. "&i" means address of i.
   int j = 3 + *p;    // *p is the contents of what the pointer p points to.
                      // In this case, *p is the same as i which equals 2.
   p = &j;            // Now p points to j. *p is now equal to j=5.
\end{verbatim}
Think of computer memory as having addresses and values stored at those
addresses.
\begin{verbatim}
                         Computer Memory
    Address (p)                                  Value (*p)
___________________                           ___________________

   234938530    address of i                        2   value of i
   395720335    address of j                        5   value of j
\end{verbatim}
So first {\tt p = 234938530}, then later {\tt p = 395720335}.
If we write {\tt (*p)++}, {\tt (*p)} and therefore {\tt j} is
incremented from 5 to 6. {\tt *} is called the {\it indirection}
or {\it dereferencing} operator.

\centerline{\bf Pointers and Arrays}

{\tt float x[5]} is an array of 5 floating point numbers. {\tt x[0]}
is a float and \verb2&x[0]2 is the address of the first element of
the array. Operators such as \verb2<, ==,2 etc. work on pointers.
Thus to set an array to zero, we can write
\begin{verbatim}
  float x[100];
  float *px;
  for(px=&x[0];px<=&x[99];px++)  //px++ points to the next element of the array
    *px=0.0;
\end{verbatim}
This is quite useful. Since \verb2&x[0]2 comes up a lot, it is often
denoted by just {\tt x}. So \verb2px=x2 is the same as \verb2px=&x[0]2.
\verb2px<=x+992 is the same as \verb2px<=&x[99]2.

\centerline{\bf Pointer Arithmetic}

{\tt px + int} is ok. For example,
{\tt px + 6} designates a place in memory that is 6 float places after 
{\tt px}. The ``6'' is not in units of bytes; it is in units of the size
of floats or whatever type {\tt px} points to. Suppose we are given
\begin{verbatim}
  float *pf;
  char *pc;
\end{verbatim}
Then if {\tt pf}=20000 (address in bytes), {\tt pf}+6=20000 + 6$\cdot$4
since each float takes 4 bytes.
Similarly if {\tt pc}=10000, {\tt pc}+6=10006 since each char takes 1 byte.
The {\tt sizeof} functions gives these sizes in bytes.
\begin{verbatim}
   sizeof(float)=4
   sizeof(char)=1
\end{verbatim}
In general the {\tt sizeof(type)} or {\tt sizeof(object)} gives the
size in bytes.
{\tt px - pf} gives an {\tt int} that is the distance apart in {\tt floats},
not in bytes.

\centerline{\bf Example: String copy}

The function {\tt strcpy} copies the string in array {\tt t} into
the array {\tt s}.
\begin{verbatim}
   void strcpy(char *s, char *t)
     {
     while ((*s=*t)!='\0')
            {
            s++;
            t++;
            }
     }
    main()
      {
      char t[]="hello";
      char s[100];
      strcpy(s,t);          //Notice that there is no "call" statement as in
                              fortran.
      cout << s << endl;    //cout knows to print the whole string "hello"
      }
\end{verbatim}
Or we could write
\begin{verbatim}
   void strcpy(char *s, char *t)
     {
     while (*s++=*t++)     // *s++ is the same as *(s++). First step:
                           // s[0]=t[0], i.e., *s=*t. Then increment. 
          ;                // ";" is a blank statement.
     }
\end{verbatim}
Since the value of \verb2'\0'2 is 0 or {\tt false}, the {\tt while}
statement will run until the end of the string is reached. (See page
31 of textbook for operator precedence.)

\centerline{\bf Function Calling, Passing Arguments by Value}

In Fortran, suppose we have
\begin{verbatim}
          subroutine blah(x)
          real*8 x
          x=3.0
          end

          program main
          real*8 y
          y=4.0
          call blah(y)                !blah replaces 4.0 by 3.0
          write(*,*) y                !prints 3.0 as y's value
          stop
          end
\end{verbatim}
{\tt x} and {\tt y} are synonyms for the same address, i.e., the same
location in memory. So if you change {\tt y}, you change {\tt x}.
\epsfbox{lec2fortran.eps}

What if you say 
\begin{verbatim}
          call blah(4.0d0)?
\end{verbatim}
This causes big problems because 4.0d0 is now 3.0d0. Later on
{\tt z=4.0d0} {\it might} give you 3.0d0 for {\tt z}!

In C, you pass arguments to functions by value:
\begin{verbatim}
#include<iostream.h>

   void blah(double x)
      {
      x=3.0;
      }
   void main()
      {
      y=4.0;
      blah(y);              //blah initially is passed the value 4.0 for x,
                            //but then sets x=3.0. blah doesn't change y.
      cout << y << endl;    //gives 4.0 as y's value
      }
\end{verbatim}
{\tt x} and {\tt y} reside in different places in memory. {\tt y}
gets copied into {\tt x}, 
the argument for {\tt blah}. This is called ``passing
by value.'' The value for {\tt y} doesn't actually change.
\epsfbox{lec2C.eps}

Fortran passes by address or reference.

Both ways of passing variables are useful. C++ lets you do both
with {\bf references}. 
\begin{verbatim}
    double x=3.14;
    double &y=x;               //A reference variable must be initialized
                               //when it is declared.
\end{verbatim}
\epsfbox{lec2ref.eps}

{\tt y} is a {\it reference} to {\tt x} which is a double variable.
{\tt y} is a synonym for {\tt x}. {\tt x} and {\tt y} refer to the
same place in memory. It acts exactly like the Fortran variable
{\tt y} in the subroutine {\tt blah}.

\begin{verbatim}
    x=2.0;        // now y=2.0
    y=3.0;        // now x=3.0
    cout << x << y << endl;     //yields 3.0 3.0
\end{verbatim}
(No {\tt *} needed for references.)

{\bf Why do we need references?} 
\begin{enumerate}
\item It is a convenient shorthand. Suppose you need to do manipulations
of \verb4x[18*i+j][32*k]4 where {\tt i, j} and {\tt k} are fixed for a
while. Then you could write
\begin{verbatim}
    double &rx=x[18*i+j][32*k];
\end{verbatim}
Now use {\tt rx} everywhere as a reference, until {\tt i} or {\tt j}
or {\tt k} changes. Then define a new reference.
For example, to construct a unit matrix, we could write
\begin{verbatim}
    double mat[100][100];
    for(i=0;i<100;i++)
      for(j=0;j<100;j++)
        {
        double &m=mat[i][j];
        if(i==j)
           m=1.0;
        else
           m=0.0;
        }
\end{verbatim}
\item References are very useful for function calls.
\begin{verbatim}
    void blah(double &x)
       {
       x=3.0;
       }
    main()
       {
       y=4.0;
       blah(y);
       cout << y << endl;   // yields y=3.0
       }
\end{verbatim}
This is really useful when you have ``big'' objects that you don't
want to copy and pass to a function. It's more efficient to just
tell the function where to find the object. But what if you say 
{\tt blah(4.0)}? You're hosed.
\end{enumerate}
After a reference variable has been declared, you can do nothing
to access the reference variable itself. That's why a reference
variable must be initialized when it is declared. Reference variables
declared as arguments to functions are initialized when the function
is called.

\centerline{\bf Constants}

In Fortran we use {\tt parameter} to set constant values. For example,
\begin{verbatim}
            parameter (pi=3.14159)
\end{verbatim}
C++ has {\tt const}. For example,
\begin{verbatim}
            const double pi=3.14159;
\end{verbatim}
This line could go anywhere, whereas in Fortran, parameter statements
are at the beginning of the program.
If later on we write {\tt pi=7.0;} we get a syntax error.

\centerline{\bf Constant Pointers}

There are
\begin{enumerate}
\item pointers to {\tt const floats}.
\begin{verbatim}
       const float pi=3.14159;  // A const variable must be initialized when
                                // it is defined (except if it is declared 
                                // with as an extern statement, in which
                                // case it is defined elsewhere).
       const float *ppi=&pi;
       *ppi=7.0;	//ERROR
\end{verbatim}

\item ``const pointers'' to floats. Const pointers can't change the
place they point to in memory.
\begin{verbatim}
       float a;
       float* const pa=&a;
       *pa=7.0;            //OK to do this
       float b;
       pa=&b;             //ERROR!
\end{verbatim}

\item ``const pointers'' to ``const floats''
\begin{verbatim}
       const float * const p = &pi;
       *p = 7.0;                     //ERROR!
       p=&b;                         //ERROR!
\end{verbatim}

You can't change anything in this case.
\end{enumerate}
The rule is that the ``const ness'' applies to the thing immediately
to the right of the {\tt const} keyword. You can also read the declaration
backward. For example, \verb2float* const pa2 can be read ``pa is a
constant pointer to a float.''

\centerline{\bf Const in Function calls}
\begin{verbatim}
    void func(const double &x)
      {x=3.0;}                   //ERROR
\end{verbatim}
{\tt const} should appear everywhere possible in function arguments.
It's more efficient if the compiler knows that those arguments won't be
changed, and it prevents bugs. For example, writing
\begin{verbatim}
    void strcpy(char* s, const char* t);
\end{verbatim}
prevents bugs.

\begin{verbatim}
    double abs(double x)       //Ok. Pass by value.
       {....}

    double abs(double &x)     //BAD! because you could change x.
 
    double abs(const double &x)   //Good way to do things.
\end{verbatim}

\centerline{\bf Function Prototypes (declarations versus definitions)}

If the program is in separate files, or if the function is defined later
in the file, you need to declare the function. A declaration tells you
the function is there but doesn't define it and tell you how
it works. An example of a declaration is 

\begin{verbatim}
    double abs(const double &x);     // The ";" replaces {}. 
                                     // The "x" is optional.
\end{verbatim}
You can put this declaration anywhere in the program before {\tt abs}
is used.

\centerline{\bf New and Delete}

In Fortran we dimension arrays as follows:
\begin{verbatim}
          parameter(maxsize=1000)
          real*8 vec(maxsize)
\end{verbatim}
This means you have to recompile every time you have a different size
for {\tt vec}. Or you just make {\tt maxsize} 
bigger than any conceivable size that {\tt vec} could need. But this wastes
memory. 

In C++, we still have to dimension arrays and allocate
memory, but we can do it efficiently by using {\tt new} as in this example:
\begin{verbatim}
   double *vec;                 //pointer to a vector
   cin >> n;
   vec = new double[n];
\end{verbatim}
This allocates 8n bytes of memory for {\tt vec} and gives you a pointer
to it. The next call to {\tt new} will give you a pointer to a new location
in memory.

{\tt delete} is used to give back the memory once the program is
finished with it. So once the program is finished with {\tt vec},
it executes
\begin{verbatim}
    delete []vec;
\end{verbatim}
and returns the allocated memory to the heap. This works not just for
arrays, but also for single objects:
\begin{verbatim}
    double *pa;
    pa=new double;
    delete pa;
\end{verbatim}
Objects created by {\tt new} don't go away until you call {\tt delete}.
For example,
\begin{verbatim}
    void badfunction()
       {
       double *px=new double[1000];
       }
\end{verbatim}
Once the program is finished executing {\tt badfunction}, it throws
away {\tt px} but the system has still set aside the memory and you
can never get it back! This is called a ``memory leak''; it's a 
C++ programmer's worst nightmare.

Once you've allocated the pointer, you can treat it like an array.
It works exactly like an array. For example,
\begin{verbatim}
    float *a;
    a=new float[100];
    for(i=0;i<100;i++)
      a[i]=1.0;
\end{verbatim}

\centerline{\bf Pointer Arrays; Pointers to Pointers}
Since pointers are variables themselves, they can be stored as
arrays just as other variables can. For example, consider
the beginning of a program that sorts lines of text alphabetically:
\begin{verbatim}
    #define MAXLINES 5000        //max number of lines to be sorted
    char *lineptr[MAXLINES];     //pointers to text lines
\end{verbatim}
{\it Aside}: The {\tt define} statement is a preprocessor 
command that replaces all subsequent occurrences of
{\tt MAXLINES} with {\tt 5000} (except if {\tt MAXLINES}
appear in quotes "{\tt MAXLINES}"). In general 
{\tt define} statements have the form
\begin{verbatim}
    #define   name   replacement text
\end{verbatim}
The preprocessor will replace all subsequent occurrences
of {\it name} with {\it replacement text}
in the source file being compiled. {\tt define} statments are often
in header (\verb2.h2) files that are included in \verb2.cc2 source files.
The {\tt replacement text} can be an expression or a statement. For example,
\begin{verbatim}
    #define  forever  for(;;)      //infinite loop

    #define  max(A,B)  ((A) > (B) ? (A) : (B))
\end{verbatim} 
Names may be undefined with \verb2#undef2.

{\it Back to arrays of pointers}: The declaration for {\tt lineptr}
\begin{verbatim}
    char *lineptr[MAXLINES];     //pointers to text lines
\end{verbatim}
says that {\tt lineptr} is an array of {\tt MAXLINES} elements, each
element of which is a pointer to a {\tt char}. That is, 
{\tt lineptr[i]} is a character pointer, and \verb2*lineptr[i]2 is the
character it points to, the first character of the {\it i}th saved text
line. Since {\tt lineptr} is itself the name of an array, it can
be treated as a pointer. Thus it is a pointer to pointers. (How's that
for confusing?) We can initialize a pointer array as follows:
\begin{verbatim}
    char *name[] = {"Dopey", "Sleepy", "Doc"};
\end{verbatim}
Notice that each string is a different length. {\tt name} goes from
{\tt name[0]} to {\tt name[2]}, and each element of {\tt name} is a pointer
to a string.

Another use for a pointer to an array is two dimensional arrays.
Given the definitions  
\begin{verbatim}
    int a[10][20];
    int *b[10];
\end{verbatim}
then \verb2a[3][4]2 and \verb2b[3][4]2 are both legal references to
a single {\tt int}. {\tt a} is a true two dimensional array;
each row of {\tt a} is has 20 int--sized elements.
However, the important advantage of the pointer array is that the
rows of the array may be of different lengths. That is, each element
of {\tt b} need not point to a twenty--element vector; some may point
to two elements, some to fifty, and some to none at all. So {\tt b}
doesn't waste memory.

%If a two--dimensional array is passed to a function, the parameter
%declaration in the function must include the number of
%columns; the number of rows is irrelevant, since what is passed is
%a pointer to an array of rows, where each row is an array of elements.
%The following are equivalent declarations:
%\begin{verbatim}
%    func(int a[10][20]);
% OR
%    func(int (*a)[20]);      
%\end{verbatim}
%The parentheses are necessary since the brackets {\tt []} have higher
%precedence than \verb2*2. With the parentheses, {\tt a}
%is a pointer to an array of 20 integers.
%Without the parentheses \verb3int *a[20]3 
%is an array of 20 pointers. In general, for a multi--dimensional
%array, only the first dimension (subscript) of an array is free;
%all the others have to be specified.

If a multi--dimensional array is passed to a function, the function
declaration typically looks like
\begin{verbatim}
     func(int a[]); or func(int *a);         //for a 1D array

     func(int a[][]); or func(int **a);      //for a 2D array

     func(int a[][][]); or func(int ***a);   //for a 3D array
\end{verbatim}
These arrays are dimensioned elsewhere in the program and passed to
the function. Here is an example of how to use new and delete for
a two dimensional array:
\begin{verbatim}
  #include <iostream.h>

  void func(int **p);
  void main()
    {
     //Create a 2D array of integers p[5][2]

     int** p;
     p=new int*[5];                //create array of 5 pointers to integers
     for(int i=0;i<5;i++)
      p[i]=new int[2];             //create row of 2 columns of integers

     func(p);                      //pass name of array without **

     for(int i=0;i<5;i++)
     delete []p[i];                //delete in reverse order of creation

     delete []p;
    }


    void func(int **p){
      int n=0;
      for(int i=0;i<5;i++)
        for(int j=0;j<2;j++)
       {p[i][j]=n++;
       cout << i << " "<<j<< " "<< p[i][j]<<endl;}
    }
\end{verbatim}



\centerline{\bf Pointers to Functions}
In C and C++, a function is not a variable, but it is possible
to define pointers to functions, which can be assigned, placed
in arrays, passed to functions, returned by functions, and so on.
A function name alone refers to its address. The following
does {\it not} declare a pointer to a function:
\begin{verbatim}
    int *pFn();
\end{verbatim}
Instead, this declares a function that returns a pointer to an
integer. The {\tt ( )} takes effect first because it has a higher
precedence than \verb2*2. To get the desired effect, parentheses
are required:
\begin{verbatim}
    int (*pFn)(float);
\end{verbatim}
Now the \verb2*2 takes effect first. This is read as ``pFn is a
pointer to a function that takes a float argument and returns an
int.'' In use, its syntax is similar to that of an array:
\begin{verbatim}
    int anotherFn(float f);      //Some function, defined somewhere
    void myFunc(float x)
      {
        int (*pFn)(float);      //Declare a pointer to a function
        pFn = anotherFn;        //A function name alone refers to its address.
        (*pFn)(x);              //Call the function pointed at by pFn
      }
\end{verbatim}
In the last line the extra parentheses are necessary when calling
\verb2*pFn2 because the precedence of {\tt ( )} is higher than that of
\verb2*2. If we had just written \verb2*pFn(x)2, the program would
interpret {\tt pFn} as a function of {\tt x} that returns a pointer
and \verb2*pFn(x)2 is the value pointed at by {\tt pFn(x)}.

Pointers to functions are used a lot in Numerical Recipes. ({\it
Numerical Recipes in C: The Art of Scientific Computing} by W. H. Press,
S. A. Teukolsky, W. T. Vetterling, and B. P. Flannery (Cambridge
Univ. Press, 1992) is an excellent text on scientfic computing techniques.
They have a homepage at http://www.nr.com where you can download
the text of the book.) For example
suppose you want to integrate a function {\tt func(x)} over {\tt x}
from {\tt a} to {\tt b} using Simpson's rule. The declaration found
in Numerical Recipes is 
\begin{verbatim}
    float qsimp(float (*func)(float), float a, float b);
\end{verbatim}
Here a pointer to {\tt func} is passed to the integration routine
{\tt qsimp}. {\tt qsimp} returns the value of the integral as a 
{\tt float}. To use {\tt qsimp}, we would write something like:
\begin{verbatim}
    float function(float);
    float integral = qsimp(function, a, b);
\end{verbatim}
Notice that the argument of {\tt qsimp} is just {\tt function},
not \verb2&function2 since the name of the function by itself
refers to the address of the function.

\end{document}

