Reputation: 664
From C++ Early Objects - Gaddis, 8th Edition. I note similar questions on SO, but none that answer this aspect. Consider this simple program:
// This program uses a pointer to display
// the contents of an array.
#include <iostream>
using std::cout;
int main(){
const int SIZE = 8;
int set[ ] = {5, 10, 15, 20, 25, 30, 35, 40};
int *numPtr; // Pointer
// Make numPtr point to the set array.
numPtr = set;
// Use the pointer to display the array elements
cout << "The numbers in set are:\n";
for (int index = 0; index < SIZE; index++) {
cout << *numPtr << " ";
numPtr++;
}
// Display the array elements in reverse order
cout << "\nThe numbers in set backwards are:\n";
for (int index = 0; index < SIZE; index++) {
numPtr--;
cout << *numPtr << " ";
}
return 0;
}
Works, I tested it! But conceptually, numPtr is pointing to the starting address of the array "set", so how does incrementing numPtr "backwards" from the starting address not cause a segfault on the first iteration of the second (reversing) for loop? Restating the question, how is numPtr "knowing" to begin at the address of the last element of the array "set"? Be gentle, I'm in Intro to CS II... thanks!
Upvotes: 1
Views: 3243
Reputation: 655
numPtr
points to the last element after finishing the first loop.Because in your loop you increment numPtr
.And in your second loop you decrement numPtr
, and after finishing it will point the first element.
Without the first loop you can reverse the set this way.
#include <iostream>
using std::cout;
int main(){
const int SIZE = 8;
int set[ ] = {5, 10, 15, 20, 25, 30, 35, 40};
int *numPtr;
numPtr = set;
cout << "\nThe numbers in set backwards are:\n";
for (int index = 0; index < SIZE ; index++) {
cout << *(numPtr+SIZE-1-index) << " ";
}
return 0;
}
Output:
The numbers in set backwards are:
40 35 30 25 20 15 10 5
Upvotes: 0
Reputation: 9881
At the beginning, numPtr
points to the beginning of the set. Then, in the first operation, you increment the numPtr
until it points to the end of the set.
When you reach the second iteration, numPtr
is at set+sizeof(set)-1
, so you can decrement it to get your set backwards.
Upvotes: 2
Reputation: 4265
At the time your second loop starts, your numPtr
points behind the last element of set
, because you increased it in your first loop.
Without the first loop, it would fail.
Upvotes: 4