/*
* Demo of arrays and pointers.
*/
#include <iostream>
using namespace std;
int main(void) {
//an array
int ar[] = {1, 2, 3, 4, 5};
//a pointer
int *ptr;
//number of elements
int n=sizeof(ar)/sizeof(ar[0]);
//set the pointer to the address of ar[0]
ptr = ar;
//loop over the array
cout << "Standard Indexing" << endl;
for(int i=0; i<n; i++) {
cout << i << ": " << ar[i] << endl;
}
//loop over the array using the pointer
cout << "Indexing the pointer" << endl;
for(int i=0; i<n; i++) {
cout << i << ": " << ptr[i] << endl;
}
//loop over this using pointer arithmetic
//the ugly way!
cout << "Ugly pointer arithmetic" << endl;
for(int i=0; i<n; i++) {
cout << i << ": " << *(ptr + i) << endl;
}
//elegant pointer arithmetic
cout << "Why you can code C very quickly" << endl;
for(ptr = ar; ptr < ar + n; ptr++) {
cout << ptr - ar << ": " << *ptr << endl;
}
return 0;
}