Exercises
Pointers #1

For each of these statements, draw a diagram showing what happens to the memory locations.

``` ITEM *p, *s, *r; ITEM  x;```

1. `p = new ITEM;`
2. `s = p;`
3. `r = NULL;`
4. `s = &x;`
5. `delete p;`
6. `p = 0;`

7. Carefully trace through the following program, using diagrams as needed, and indicate the output.

```{
int *a, *b, *c;
a = new int;
*a = 10;
b = a;
c = new int;
*c = *a;
cout << setw(4) << *a << *b << *c << endl;
*a = 23;
cout << setw(4) << *a << *b << *c << endl;
delete b; delete c;
}
```

8. Draw diagrams to illustrate the situation after each statement at right is executed.

```struct node
{
int data;
node*next;
};

int main ( )
{
node *s, *t;
s = new node;
s -> data = 12;
t = new node;
t -> next = s;
t -> data = 23;
s -> next = NULL;
delete t; delete s;
return 0;
}
```

9. Draw a diagram and state the output of each segment of code below.

• ``` node *p, *s; p = new node; s = new node; p -> data = 5; s -> data = 6; delete p; p = s; p ->data = 1; cout << p ->data << " " << s ->data; delete p; p = NULL; ```

• ``` node *p, *s; p = new node; p ->data = 3; s = new node; s ->data = 2; p = new node; p ->data = s ->data; s ->data = 0; s ->next = NULL; p ->next = s; cout << p ->data << " " << s ->data; delete p; delete s; ```

10. Which of 9(a) and 9(b) leaves inaccessible node? a dangling pointer?

Continue to:  Unit 5 / Prev / Next