Worksheet Pointer PDF
Worksheet Pointer PDF
Page 1|4
EXERCISES ON POINTERS
5. What is the output if the following code fragment is embedded in a complete C++
program?
5.1.
int *p1, v1 = 0;
p1 = &v1;
*p1 = 42;
cout << v1 << endl;
cout << *p1 << endl;
5.2.
int *p1, *p2;
p1 = new int;
*p1 = 42;
p2 = p1;
cout<< "*p1 = " << *p1 << endl;
cout<< "*p2 = " << *p2 << endl;
*p2 = 53;
cout<< "*p1 = " << *p1 << endl;
cout<< "*p2 = " << *p2 << endl;
p1 = new int;
*p1 = 88;
cout<< "*p1 = " << *p1 << endl;
cout<< "*p2 = " << *p2 << endl;
cout<< "Make sure you understood the logic!\n";
5.3.
int *p1, *p2;
p1 = new int;
p2 = new int;
*p1 = 10;
*p2 = 20;
cout << “*p1= “<<*p1 << ", " << “*p2 =“<<*p2 << endl;
p1 = p2;
cout << “*p1= “<<*p1 << ", " << “*p2 = “<<*p2 << endl;
*p1 = 30;
cout << “*p1= “<<*p1 << ", " << “*p2 = “<<*p2 << endl;
Page 2|4
EXERCISES ON POINTERS
5.4.
int *p1, *p2;
p1 = new int;
p2 = new int;
*p1 = 10;
*p2 = 20;
cout << “*p1= “<<*p1 << ", " << “*p2 =“<<*p2 << endl;
*p1 = *p2;
cout << “*p1= “<<*p1 << ", " << “*p2 =“<<*p2 << endl;
*p1 = 30;
cout << “*p1= “<<*p1 << ", " << “*p2 =“<<*p2 << endl;
5.5.
typedef int* IntPtr; //Note that to use typedef #include <cstddef> is required
int main( ) {
IntPtr p;
int arr[10];
int index;
for (index = 0; index < 10; index++)
arr[index] = index;
p = arr;
for (index = 0; index < 10; index++)
cout << p[index] << " ";
cout << endl;
for (index = 0; index < 10; index++)
p[index] = p[index] + 1;
for (index = 0; index < 10; index++)
cout << arr[index] << " ";
cout << “\nEnd”;
5.6.
int arr[10];
int *p = a;
for (int i = 0; i < 10; i++)
arr[i] = i;
for (int i = 0; i < 10; i++)
cout << p[i] << ", ";
cout << “End”;
Page 3|4
EXERCISES ON POINTERS
5.7.
int array_size = 10;
int *a;
a = new int [array_size];
int *p = a;
for (int i = 0; i < array_size; i++)
a[i] = i;
p[0] = 10;
for int (i = 0; i < array_size; i++)
cout << a[i] << ", ";
cout << “End”;
5.8.
int arraySize = 10;
int *a;
a = new int[arraySize];
for (int i = 0; i < arraySize; i++)
*(a + i) = i;
for (int i = 0; i < arraySize; i++)
cout << a[i] << ", ";
cout << “End”;
5.9.
int arraySize = 10;
int *a;
a = new int[arraySize];
for (int i = 0; i < arraySize; i++)
a[i] = i;
while (*a < 9)
{
a++;
cout << *a << ", ";
}
cout << “End”;
6. Write a type definition for pointer variables that will be used to point to
dynamic arrays. The array elements are to be of type char. Call the type
CharArray.
7. Suppose your program contains code to create a dynamic array as shown below so
that the pointer variable entry is pointing to this dynamic array. Write code to fill this
array with ten numbers typed in at the keyboard.
int *entry;
entry = new int[10];
Page 4|4