1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <iostream>
using namespace std;
void f(int* &startOfArrayRef, int* endOfArray){ // on entry, startOfArrayRef points to the [0] (i.e. first) and endOfArray to the [4] (i.e. last) element
*startOfArrayRef = 16; // array becomes { 16, 10, 15, 20, 25 }
startOfArrayRef = startOfArrayRef+2; // startOfArrayRef now points to the [2] element (i.e. the third)
*endOfArray = (*startOfArrayRef)%3; // the last element becomes 15 % 3, which is 0; array now { 16, 10, 15, 20, 0 }
endOfArray = startOfArrayRef; // both pointers are now pointing to the middle element
*endOfArray = 2*(*(endOfArray-1)); // the middle element becomes twice the [1] (i.e. second ) element; array now { 16, 10, 20, 20, 0 }
}
int main(){
int a[5] = {5, 10, 15, 20, 25};
int* startOfArray = a;
int* endOfArray = &a[4];
f(startOfArray,endOfArray); // after this, array is { 16, 10, 20, 20, 0 };
// startOfArray passed by reference: points to [2] element on return;
// endOfArray passed by value: still points to last element
for (int i=0; i<5; i++)
cout << a[i] << " "; // The loop ends HERE
cout << "\n" << *startOfArray; // the [2] (i.e. third) element is 20
cout << "\n" << *endOfArray; // the last element is 0
return 0;
}
|