A new situation.
The
new int[ARRAY]
allocates a block of memory dynamically that is large enough to hold ARRAY integers. The block is effectively an array of ARRAY integers. It has no name, but lets call it 'fubar'.
The
new
returns the address of the memory block. The address of integer
fubar[0]
. You store that address into pointer 'travel'.
After line 5
travel == &(fubar[0])
.
On first time on line 11 you do read integer value from
miles[0]
and write it to
*travel
. To
integer at travel
. To
travel[0]
. To
fubar[0]
.
Then, on line 12 you do change the
travel
. You update it to point to
fubar[1]
.
Therefore, after the first iteration of the loop
travel == &(fubar[1])
.
Q: Where does the travel point to after the loop, at line 14?
A:
travel == &(fubar[ARRAY]) == fubar + ARRAY
Alas, the fubar has only ARRAY elements, and the last of them is
fubar[ARRAY-1]
.
The fubar + ARRAY is not within the fubar block. It is after the block. We have no idea what is in there.
The second loop prints (the undefined junk) value of
fubar[ARRAY]
ARRAY times. You read from address that has not been allocated to you. That is an
out of range error.
On line 20 you want to deallocate an "array of integers" memory block that starts from address
fubar + ARRAY
. You have no allocated block at that address. Trying to give away something that isn't yours can and should crash.
The block that you have is at address
travel - ARRAY
.
1 2 3 4 5 6 7 8 9
|
for ( int i = 0; i < ARRAY; ++i )
{
travel[i] = miles[i];
}
for ( int i = 0; i < ARRAY; ++i )
{
cout << travel[i] << ", ";
}
|
You can use pointers too, but you may not lose the pointer that points to the start of the block in the process:
1 2 3 4
|
for ( int* tram = travel; tram != (travel+ARRAY); ++tram )
{
cout << *tram << ", ";
}
|