Pointers support normal arithmetic, so if you know the value of k
involved, you can just subtract that value to get back to the beginning of the array.
If you don't know the value of k
, you might be able to get by if you know know unique value that signals the beginning of the array.
If you don't know either of those, you're pretty much out of luck. C++ doesn't provide a way to find the beginning of an array given only a pointer to some arbitrary point inside that array.
As an aside, note that the code you've give using while (ptr)
doesn't really work for traversing to the end of the array either. It tries to keep going until incrementing the point gives a null pointer, which might never happen--and even if it does, there's a pretty good chance of the pointer going well past the end of the array first anyway.
Given the situation you describe, I'd consider (if at all possible) passing the array itself rather than a pointer:
template <class T, size_t N>
void subRoutine(T (&array)[N]) {
for (int i=0; i<N; i++)
process(array[i]);
}
You'd invoke this something like: subRoutine(arr);
The compiler will deduce the size of arr
for you, so you don't need to pass an extra parameter to specify the size.