I was thinking about how to traverse an array without an int
iterator, and I'm curious if my answer is good/bad.
The first for loop simply populates each element of the array.
The second for loop traverses through the array. The int
pointer, curr
, initially points to the first address of the array then goes on to momentarily hold the address of each element of the array. The int
pointer, ptrLastElement
, contains the address of the last element of the array arr
.
The check condition is essentially the difference of the address contained in ptrLastElement
and the address contained in curr
. If the difference is less than 0, then we've ran out of elements to display.
My main questions are:
- Would this idea ever be useful?
- Is this a terrible idea?
- Did I do anything incredibly stupid?
- How can I improve this and/or make it more generic?
main.cpp
#include <iostream>
int main()
{
const size_t SIZE = 10;
int arr[SIZE];
int * ptrLastElement = arr + (SIZE-1);
// Populate the array, arr, using int iterator
for (int i = 0; i < SIZE; ++i)
{
arr[i] = i;
}
// Traversing arr using a pointer
for (int * curr = arr; (ptrLastElement - curr) >= 0 ; ++curr)
{
std::cout << curr << "\t" << *curr << std::endl;
}
return 0;
}
(ptrLastElement - curr) >= 0
looks like a less readable version ofcurr <= ptrLastElement
\$\endgroup\$curr <= ptrLastElement
is definitely more readable and it doesn't require computation. \$\endgroup\$