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.

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


Continue to:  Unit 5 / Prev / Next