Array Access Using Pointers


//  this program shows how pointer notation can be used to access
//  the elements of an array

#include <iostream.h>

int main()
{
	int nums[10];
	int *intptr;

//  store values in the array
	for (int i = 0 ; i < 10 ; i++)
		nums[i] = (i + 1) * 2;

//  print out the numbers in the array
	for (i  = 0 ; i < 10 ; i++)
		cout << nums[i] << "    ";
	cout << endl << endl << endl;

//  print out the address and contents of each array element
//  using pointers
	for (intptr = nums ; intptr < nums + 10 ; intptr++)
		cout << intptr << "        " << *intptr << endl;
	cout << endl;

//  print out the address and contents of each array element
//  using pointers
	intptr = nums;
	for (i = 0 ; i < 10 ; i++)
		cout << (intptr + i) << "        " << *(intptr + i)
		                                   << endl;
	cout << endl;

	return 0;
}

Output:

2    4    6    8    10    12    14    16    18    20


0x75ef23c8        2
0x75ef23ca        4
0x75ef23cc        6
0x75ef23ce        8
0x75ef23d0        10
0x75ef23d2        12
0x75ef23d4        14
0x75ef23d6        16
0x75ef23d8        18
0x75ef23da        20

0x75ef23c8        2
0x75ef23ca        4
0x75ef23cc        6
0x75ef23ce        8
0x75ef23d0        10
0x75ef23d2        12
0x75ef23d4        14
0x75ef23d6        16
0x75ef23d8        18
0x75ef23da        20

Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2001