/**************************************************************/
// R. A. Hillyard
// pointer04.cpp
// November 2001
//
// Program to demonstrate the relationship between pointers and arrays
// an array name is really a pointer
/**************************************************************/
#include<iostream>
using namespace std;
int const MinSize = 5;
int main()
{
int a[MinSize]; //array of MinSize ints
int *ptr1; //pointer to type int
int index = 0; //used for loop counter
//assign values to array using array name
for(index = 0; index < MinSize; index++)
{
a[index] = 2 * index ;
}
//assign pointer to point at array
// note that I do not need the address of & operator
ptr1 = a;
//print value of array elements using the pointer with index
cout << "First time: \n";
for(index = 0; index < MinSize; index++)
{
cout << "index = " << ptr1[index] << endl;
}
//assign value to array elements by dereferencing the pointer
for(index = 0; index < MinSize; index++)
{
*ptr1++ = 3 * index;
}
ptr1=a; //need to reset pointer to start of a;
//print value of array elements by dereferencing the pointer
cout << "\nSecond time: \n";
for(index = 0; index < MinSize; index++)
{
cout << "index = " << *ptr1++ << endl;
}
//assign value of array elements using array name like a pointer
for(index = 0; index < MinSize; index++)
{
*(a+index) = 2 * index ;
//*a+index = 2 * index ; causes compiler error => "not an lvalue"
}
//print value of array elements using array name like a pointer
cout << "\nThird time: \n";
for(index = 0; index < MinSize; index++)
{
cout << "index = " << *(a+index) << endl;
}
}
/***********************Program Output*************************/
First time:
index = 0
index = 2
index = 4
index = 6
index = 8
Second time:
index = 0
index = 3
index = 6
index = 9
index = 12
Third time:
index = 0
index = 2
index = 4
index = 6
index = 8