Pointer Arrays

Pointer arrays contain pointers to other data types, such as an int or char.

 

Declared as per a normal pointer, appended by the array subscript square brackets:

 

int *myPtr[N] ; //where N indicates the number of pointers required in the array

 

#include <iostream>
using namespace std;

int main () {

	int myArr[] = {10,20,30,40,50} ;

	int arrSize = sizeof(myArr) / sizeof(int) ;

	int *arrPtr[arrSize] ;

	for (int i = 0 ; i < 5 ; i++) {

		arrPtr[i] = &myArr[i] ;

		cout << "Array element ["<< i <<"] via pointer array: " << *arrPtr[i] << endl ;
	}

	return 0;
}

Compile & Run:

Array element [0] via pointer array: 10
Array element [1] via pointer array: 20
Array element [2] via pointer array: 30
Array element [3] via pointer array: 40
Array element [4] via pointer array: 50

 

 

Similarly, applied as a char pointer array to point to strings:

#include <iostream>
using namespace std;

int main () {

	char *myArr[5] = {"Debbie", "Noko", "Jimmy" ,"Julia", "Vanessa"} ;

	for (int i = 0 ; i < 5 ; i++) {

		cout << "Array element ["<< i <<"] via pointer array: " << myArr[i] << endl ;
	}

	return 0;
}

Compile & Run:

Array element [0] via pointer array: Debbie
Array element [1] via pointer array: Noko
Array element [2] via pointer array: Jimmy
Array element [3] via pointer array: Julia
Array element [4] via pointer array: Vanessa

Leave a Reply