You are on page 1of 3

TK1924 Tutorial 02 Answer - Pointers 1

1. What is the output of the following C++ code?

a. int x, y;
int *p = &x;
int *q = &y;
*p = 35; *q = 98;
*p = *q;
cout << x << “ “ << y << endl;
cout << *p << “ “ << *q << endl;

Answer: 98 98
98 98

b. int x, y;
int *p = &x;
int *q = &y;
x = 35; y =46;
p = q;
*p = 78;
cout << x << “ “ << y << endl;
cout << *p << “ “ << *q << endl;

Answer: 35 78
78 78

c. int *p; int *q;


p = new int;
q = p;
*p = 46;
*q = 39;
cout << *p << “ “ << *q << endl;

Answer: 39 39

d. int *p; int *q;


p = new int;
*p = 43;
q = p;
*q = 52;
p = new int;
*p = 78;
q = new int;
*q = *p;
cout << *p << “ “ << *q << endl;

Answer: 78 78

e. int list[6] = {11, 12, 13, 14, 15, 16};


TK1924 Tutorial 02 Answer - Pointers 2

int *p = list;
cout << *(list = i) << endl;
cout << list[i] << endl;
cout << *(p+i) << endl;
cout << p[i] << endl;

Answer: 11
11
11
11

f. int x, *p, *q;


p = new int[10];
q = p;
*p = 4;
for (int j=0; j<0; j++)
{
x = *p;
p++;
*p = x + j;
}
for (int k = 0; k < 10; k++)
{
cout << *q << “ “;
q++;
}
cout << endl;

Answer: 44 57 10 14 19 25 32 40

g. int j, *p;
p = new int[10];
p[0] = 10;
for (j = 1; j < 10; j++)
p[j] = p[j – 1] + 5;
for (j = 0; j < 10; j++)
cout << p[j] << “ “;
cout << endl;

Answer: 10 15 20 25 30 35 40 45 50 55

h. int *p, *q, i;


p = new int[5];
p[0] = 5;
for (i=1; i<5; i++)
p[i] = p[i-1] + 2 * i;
cout << “array p: ”;
for (i=0; i<5; i++)
cout << p[i] << “ “;
TK1924 Tutorial 02 Answer - Pointers 3

cout << endl;


q = new int[5];
for (i=0; i<5; i++)
q[i] = q[4-i];
cout << “array q: ”;
for (i=0; i<5; i++)
cout << q[i] << “ “;
cout << endl;

Answer: array p: 5 7 11 17 25
array q: 25 17 11 7 5
2. Given the declaration:

int num = 6;
int *p = &num;

Which of the following statements increment(s) the value of num?

a. p++
b. (*p)++

c. num++

d. (*num)++

Answer: b, c

3. Draw a diagram to show the memory configuration after the following statements are executed:

int i,j;
int *p;
int *q;
p = new int[5];
q= new int[5];
p[0] = 10;

for (int i=1; i <5; i++)


{
p[i] = p[i-1] + 5;
}
for (int j=0; j<5; j++)
{
q[j] = p[4-j];
}

You might also like