Array Echo With Pointers
/* * Read some integers into an array, then echo them, using pointers. */ #include <iostream> using namespace std; const int ARRMAX = 100; int main() { // Read them in. int arr[ARRMAX]; /* Array of numbers. */ int *scan = arr; cout << "Enter some integers: " << endl; while(cin >> *scan) ++scan; int *end = scan; // Print them back out again. cout << "===============" << endl; for(scan = arr; scan < end; ++scan) { cout << *scan << " "; } cout << endl; // Array iterators can be compared, the result reflecting their // position, and they can incremented by numbers other than 1. // Here, we go up the even-numbered ones, then the odd ones. scan = arr; while(scan < end) { std::cout << *scan; scan += 2; if(scan < end) { std::cout << " "; } } std::string sep = "|"; for(scan = arr + 1; scan < end; scan += 2) { std::cout << sep << *scan; sep = " "; } std::cout << "\n===============" << std::endl; }

Here we use a native array with pointers. This program is essentially the same as the second array container example, since pointers behave very much like iterators. In fact, iterators were designed to behave like pointers.

Pointers are declared using an asterisk (which we usually call a “splat” to save time). The declaration

int *scan;

declares scan to be a pointer to integer, which can serve as an iterator over arrays of integer. Arrays don't have a begin() method, instead the name of an array represents a constant pointer to position zero in the array. That's why the initialization in

int *scan = arr;
sets the value of scan to the first item in the array, just as the assignment
std::array<int, 100>::iterator scan = arr.begin();
sets scan to the first item in arr.

Native arrays do not have an end() method either, but if N is the size of array, array + N is similar to end(): a pointer one past the last member. They also don't have a size() method, so you have to know N separately.