Array of Pointers

Declare a pointer array with the number of elements to be pointed to:

#include <stdio.h>

int main() {

	int myArray[6] = {12, 14, 17, 42, 63, 70} ; //initialise an array
	int *myPtr[6] ; //declare the pointer as an array of 6 pointers

	for (int i = 0; i < 6; i++) { //iterate through the array

		myPtr[i] = &myArray[i]; // assign the address of the array element to the pointer array element

		printf("myArray[%d] contains %d \n", i, *myPtr[i]) ;
	}
	Return 0;
}

Compile & Run:

myArray[0] contains 12
myArray[1] contains 14
myArray[2] contains 17
myArray[3] contains 42
myArray[4] contains 63
myArray[5] contains 70

 

 

 

Or through a char array:

#include <stdio.h>

int main() {

	char *myArray[] = {"Casey Stoner", "Danny Pedrosa", "Valentino Rossi", "Jorge Lorenzo"} ;

	for (int i = 0; i < 4; i++) { //iterate through the array

		printf("myArray[%d] contains %s \n", i, myArray[i]) ;

	}
	return 0;
}

Compile & Run:

myArray[0] contains Casey Stoner
myArray[1] contains Danny Pedrosa
myArray[2] contains Valentino Rossi
myArray[3] contains Jorge Lorenzo

Leave a Reply