Vision Group Logo

Pointers


This webpage aims to demonstrate the use of pointers. A simple example is given, to aid understanding the principles, and would be used, for example when you wished to sort an array of objects temporarily, still maintaining their original ordering. This avoids copying the objects.


testpointers.cpp testpointers2.cpp
#include <iostream>

using namespace std;

int main()
{
	unsigned int i, j;
	unsigned int N = 10;
	int **array;
	array = new (int*)[N];
	for(i = 0; i < N; i++){
		array[i] = new int(i);
	}
	for(i = 0; i < N; i++){
		cout << *array[i] << endl;
	}
	int **temp_array;
	temp_array = new (int*)[N];
	for(i = 0; i < N; i++){
		temp_array[i] = array[i];
	}
	int* temp_ptr;
	temp_ptr = temp_array[5];
	temp_array[5] = temp_array[2];
	temp_array[2] = temp_ptr;
	for(i = 0; i < N; i++){
		cout << *temp_array[i] << endl;
	}
	for(i = 0; i < N; i++){
		cout << *array[i] << endl;
	}
	return 0;
}
#include <iostream>

using namespace std;

int main()
{
	unsigned int i, j;
	unsigned int N = 10;
	int *array;
	array = new (int)[N];
	for(i = 0; i < N; i++){
		array[i] = i ; 
	}
	for(i = 0; i < N; i++){
		cout << array[i] << endl;
	}
	int **temp_array;
	temp_array = new (int*)[N];
	for(i = 0; i < N; i++){
		temp_array[i] = &(array[i]);
	}
	int* temp_ptr;
	temp_ptr = temp_array[5];
	temp_array[5] = temp_array[2];
	temp_array[2] = temp_ptr;
	for(i = 0; i < N; i++){
		cout << *temp_array[i] << endl;
	}
	for(i = 0; i < N; i++){
		cout << array[i] << endl;
	}
	return 0;
}


And their use in a sorting algorithm:
testsort.cpp
#include <iostream>

using namespace std;

void iSort(int* array);

int main()
{
	int *array1;
	array1 = new int[10];
	array1[0] = 4;
	array1[1] = 6;
	array1[2] = 8;
	array1[3] = 4;
	array1[4] = 2;
	array1[5] = 90;
	array1[6] = 1;
	array1[7] = 12;
	array1[8] = 8;
	array1[9] = 2;

	cout << "\nBefore function call values are: ";
	for (int i = 0; i < 10; i++)
		cout << array1[i] << " ";

	iSort(array1);

	cout << "\nAfter function call values are: ";
	for (int i = 0; i < 10; i++)
		cout << array1[i] << " ";
	cout << endl;
	delete[] array1;
	return 0;
}

void iSort(int* array)
{
	int N = 10;
	int curr, key, pix;
        int *tmp_ptr;
	int **tmparray;
	
	tmparray = new (int*)[N];
	for (int j = 0; j < N; j++)
		tmparray[j] = &(array[j]);

	for(int i = 1; i < N; i++)
	{
		curr = i;
		pix = *tmparray[curr-1];
		key = *tmparray[curr];
		while( curr > 0 && pix > key ){
			tmp_ptr = tmparray[curr];
			tmparray[curr] = tmparray[curr-1];
			tmparray[curr-1] = tmp_ptr;
			curr--;	
			if(curr > 0) pix = *tmparray[curr-1];
		}

	}
	cout << "\nAfter sorting in the function values are: ";
	for (int k = 0; k < N; k++)
		cout << *tmparray[k] << " ";
	cout << "\nMedian: " << *tmparray[5];
}

Chris Needham - Leeds Vision Group, School of Computing. 20-Feb-2003.