Introduction to Pointers and Notes

1) Draw a diagram showing what happens in memory after each statement.

```double *ptr1, ptr2;
double realNum = 1.234;
ptr1 = new double;
*ptr1 = 4.2;
ptr2 = ptr1;
*ptr2 = -4.09;
if (*ptr1 == 4.2) cout << "Unchanged";
else cout < "Changed";
if ( ptr1 == ptr2) cout << "Equals";
else cout << "Not Equal";
prt2 = NULL;
if (ptr1 != NULL)
delete ptr1;
ptr1 = &realNum;
```

2) Write a function to interchange pointers `p` and `r`, so that after the function is performed `p` will point to the item to which `r` formerly pointed, and vice versa.

Reference C++ for You++, Litvin, pp.179-198:

• "dynamic allocation".
• Syntax of a pointer variable
• NULL
• Arrow Syntax
• Traversing the list
• Develop function PrintList

``` struct node {    int info;    node*next; }; node*p; ```

Creating new nodes
`p = new node;`

Deleting of nodes
`delete p;`

The best time to use the new procedure is when you have some information to store into a node, not before. Pointers may be declared in variable declarations, but do not point to any information until new. Likewise delete frees the memory location, and does require a new declaration for use again.

3) Draw a diagram showing the situation in memory after execution of each of the statements in the following program that performs a series of demonstrations.

```#include <iostream.h>
#include "apstring.h"
struct node
{
apstring info;
node *next;
};
int main( )
{
node *A, *B;
A = new node;
B = new node;
B -> info = "Sosa";
B -> next = NULL;
A -> info = "McGwire";
A -> next = B;
cout << A->next->info;
delete B;
delete A;
return 0;
}
```

Continue to:  Unit 5 / Prev / Next