#include <iostream>
usingnamespace std;
void increment_all (int* start, int* stop)
{
int * current = start;
while (current != stop) {
++(*current); // increment value pointed
++current; // increment pointer
}
}
void print_all (constint* start, constint* stop)
{
constint * current = start;
while (current != stop) {
cout << *current << '\n';
++current; // increment pointer
}
}
int main ()
{
int numbers[] = {10,20,30};
increment_all (numbers,numbers+3);
print_all (numbers,numbers+3);
return 0;
}
Im particularly confused about the (numbers+3) argument. That would make it the numbers[3] element in the array which doesn't even exist. So how is it being passed as an argument?
I dont think commenting is the problem here. I got this code directly form the tutorials section of this website: http://www.cplusplus.com/doc/tutorial/pointers/ (see section "Pointers and Const")
Comments is part of the problem, for one thing there is no description of what the code does. Good comments would keep you from asking what your asking...
int numbers[] = {10,20,30};
increment_all (numbers,numbers+3);
Im particularly confused about the (numbers+3) argument. That would make it the numbers[3] element in the array which doesn't even exist. So how is it being passed as an argument?
No that would make it the third element in the array and that would be numbers[2], not numbers[3]. Remember arrays start at zero and end at size - 1. So your valid array indexes would be 0, 1, 2.
How can you have address of an element past the last element? Thats what im confused about. Hows does numbers + 3 even exist?
in c++, it is legal to point to an element in an array or one past the end of an array. NOWHERE ELSE
But it is undefined behavior to try to dereference this address as it points to a memory that does not exist.
it is mainly used as a control value in transversing arrays.
so in your case,
1 2 3 4 5 6 7 8 9 10
numbers + 0 ==> you can take, dereference this address
numbers + 1 ==> you can take, dereference this address
numbers + 2 ==> you can take, dereference this address
// one past the end
numbers + 3 ==> you can only take, but do not dereference this address
// 2 past the end
numbers + 4 ==> INVALID
// three past the end
numbers + 5 ==> INVALID