CS 3358 (Data Structures and Algorithms) by Lee S. Koh

Drills and Challenges on
Pointers (Part 1)
solutions - for your reference )
( do let me know if you spot any errors )






01
Draw a picture of memory after these statements:





int i = 42, k = 80;
int* p1 = &i, *p2 = &k;
*p1 = *p2;


02
Draw a picture of memory after these statements:

int i = 42, k = 80;
int* p1 = &i, *p2 = &k;
p1 = p2;


03
Here is a function declaration:

void goo(int *x, int *y)
{
   int z = *x;
   *x = *y;
   *y = z;
   x = y;
}

Draw a picture of memory after these statements:

int i = 1, k = 2;
int *p1 = &i, *p2 = &k;
goo(p1, p2);


04
Consider the following statements:

int *p;
int i;
int k;
i = 42;
k = i;
p = &i;

After these statements, which of the following statements will change the value of i to 75?

(A) k = 75;
(B) *k = 75;
(C) p = 75;
(D) *p = 75;
(E) Two or more of the answers will change i to 75.


05
Consider the following statements:

int i = 42, j = 80;
int *p1 = &i, *p2 = &j;
*p1 = *p2;
cout << i << j << endl;

What numbers are printed by the output statement?

(A) 42 and then another 42
(B) 42 and then 80
(C) 80 and then 42
(D) 80 and then another 80


06
What is printed by these statements?

int i = 1, k = 2;
int *p1 = &i, *p2 = &k;
p1 = p2;
*p1 = 3;
*p2 = 4;
cout << i;

(A) 1
(B) 2
(C) 3
(D) 4


07
What is printed by these statements?

int i = 1, k = 2;
int* p1 = &i, *p2 = &k;
p1 = p2;
*p1 = 3;
*p2 = 4;
cout << k;

(A) 1
(B) 2
(C) 3
(D) 4


08
What is printed by these statements?

int i = 1, k = 2;
int* p1 = &i, *p2 = &k;
*p1 = *p2;
*p1 = 3;
*p2 = 4;
cout << i;

(A) 1
(B) 2
(C) 3
(D) 4


09
Here is a function declaration:

void goo(int* x)
{
   *x = 1;
}

Suppose that a is an int* variable pointing to some integer, and *a is equal to zero. What is printed if you print *a after the function call goo(a)?

(A) 0
(B) 1
(C) address of a
(D) address of x
(E) None of the above