POINTER EXERCISES
1.
What
is printed by the following code?
#include<iostream>
using namespace std;
void main()
{
int *p1, *p2;
int number, amount;
number
= 0;
amount
= 25;
cout
<< number << ' ' << amount
<< endl;
p1 =
&number;
cout
<< number << ' ' << *p1
<< endl;
p2 =
p1;
cout
<< number << ' ' << *p1
<< ' ' << amount<< ' ' << *p2 << endl;
*p2
= 509;
cout
<< number << ' ' << *p1
<< ' ' << amount << ' ' << *p2 << endl;
}
2.
A
C++ program contains the following
statements:
float a,*pa;
float b, *pb;
float c;
a = 3.0;
b = 1.9;
pa = &a;
*pa = 3*a;
pb = &b;
*pb += 0.5;
c = *pa +*pb;
Suppose each floating-point number occupies 4 bytes of
memory. Assume further that the address
of variable a is 128800, the address of variable b is 128804, and the address of variable c is
128808.
Draw a layout of memory, its
variables and its pointers. Then answer
the following questions.
ii) What value is
assigned to pa?_______________________
ii) What value
is represented by *(&a)? ________________________
iii) What
value is represented by *pa? __________________________
iv) What value is represented by &(*pb)? _______________________
v) What value is assigned
to c? ____________________________
vi) What value
is assigned to pb? ___________________________
3. Suppose the
following:
int array[25];
int *p;
How can we use the
pointer p to set all
elements of array to zero?
4. What is printed by
the following code?
#include<iostream>
using namespace std;
int main()
{
int *p, *q;
p = new int;
q = new int[4];
*p =
50;
*q =
25;
for (int i = 1; i
< 4; i++)
q[i]
= *p;
for (int i = 0; i
< 4; i++)
cout
<< q[i] << ' ';
delete p;
delete [] q;
}
5. Pointers to classes
#include<iostream>
using namespace std;
class twoNums
{
public:
void setOne(int);
void setTwo(int);
void nicePrint();
private:
int one;
int two;
};
int main()
{
twoNums
*ptr;
ptr
= new twoNums;
(*ptr).setOne(56);
(*ptr).setTwo(23);
(*ptr).nicePrint();
//another way
ptr->setOne(45);
ptr->setTwo(87);
ptr->nicePrint();
}
void twoNums::setOne(int
x)
{
one
= x;
}
void twoNums::setTwo(int
x)
{
two
= x;
}
void twoNums::nicePrint()
{
cout
<<"*
* * ONE: " <<
one << " * *
*" << endl;
cout
<<"*
* * TWO: " <<
two << " * *
*" << endl;
}
6.
// example on constructors and destructors from: //http://www.cplusplus.com/doc/tutorial/classes/
7.
// pointer to classes
example from
//http://www.cplusplus.com/doc/tutorial/classes/