Comparing pointers and references
T÷lvunarfrŠ­i 2, spring 2005


Defining pointers:
    <TYPE> *<pointer name>;
Here <TYPE> can be a predefined type such as int, float, or a user-defined class. Example:
    int *p;
    CAT *t;

Defining references:

    <TYPE> &<reference> = <variable name>;
Here <TYPE> can be as above. <variable name> is a defined variable of the same type. Example:
    int &magn = fjoldi;
Now magn is another name of the variable fjoldi. You can use both name equally.


When references have been defined they can be used as another name of the variable they were attached to.

There are two operators that are connected to pointers. To get what the pointers point to, you use the operator "*". Example:

    float *p;		// p is a pointer to float
    p = new float;		// p is made to point to an unnamed float-location
    *p = 2.5;		// what p points to (i.e. the unnamed location) is given
    			//  the value 2.5
You can get the address of all variables with the operator "&". All variables are stored in memory and thus have addresses. We can put these addresses into pointer variables:
    int i;		// i is an int variable
    int *p = &i;		// p is an int pointer and is made to point to i
    			//  i.e. the address of i is put into p
Note that pointers are variables also and thus have addresses like other variables. We can define "pointers to pointers to int". These are pointers that only point to "pointers to int" (or int *). Example:
    int i;
    int *p = &i;
    int **q = &p;		// q is a pointer to int-pointers and is made to point to p
    i = 5;		//
    *p = 5;		// These three statements are all equivalent
    **q = 5;		//
Note that because references are just another names of a variable then both the names have the same address. Example:
    int fjoldi;
    int &magn = fjoldi;	// magn is another name for fjoldi
    int *p;
    p = &fjoldi;		//
    p = &magn;		// There two statements are completely equivalent
You can try to type in the example above and then print out &fjoldi and &magn. You should get the same address.

Some more examples

Assume that p is a pointer to int (i.e. defined with: "int *p;"). Let us look at the meaning of a few statements:
    *p = a;		// what p points to is set as the value of a
    			//  a has to be the same type as the thing p points to, i.e. int
    			//  we also assume that p points to a memory location that we are allowed to change
    *p = &a;		// what p points to is set to the address of a
    			//  since p is a pointer to int and &a is an address then this does not
    			//  work (i.e. an address goint into an integer location)
    p = &a;		// p gets the address of a
    			//  then a must be an int variable, since p can only point to int-locations
    p = a;		// p gets the value in a
    			//  then a must be an int pointer also (i.e. defined with "int *a;")

hh (hja), January, 2005.