Your book is.... well.... This is a confusing assignment. The only way to make this work is to pass the pointer to the array by reference. This is kind of clunky. A more reasonable way would have been to just return the pointer (although passing ownership like this in
any form is generally a bad idea... so the whole concept of this assignment is kind of bad)
Anyway.. ranting over. Here's a simplified example of the difference between passing by value and passing by reference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
void byval(int v) // creates a COPY of the passed in variable
{
v = 5; // modifying v here will NOT modify the original variable, because 'v' is its own copy
}
void byref(int& r) // creates a REFERENCE to the passed in variable
{
v = 5; // changing v here WILL modify the original variable, because 'v' is referring to it
}
int main()
{
int foo = 0;
byval(foo);
cout << foo; // prints "0" as you'd expect
byref(foo);
cout << foo; // prints "5" as you might expect
}
|
So... to pass a value in to a function and expect that function to change that value... you have to pass it by reference.
Why this is weird in your case is because it's expecting you to pass a
pointer by reference. Now... pointers are a little tricky, but they work the same way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
int zero = 4;
int five = 5;
void byval(int* p) // p is a copy of the passed in pointer
{
p = &five; // make p point to five. But will not change what the original pointer pointed to
}
void byref(int*& rp) // rp is a reference to the pointer
{
rp = &five; // this WILL modify the original pointer
}
int main()
{
int* ptr = &zero;
cout << *ptr; // prints "0"
byval(ptr);
cout << *ptr; // prints "0" (ptr has not changed)
byref(ptr);
cout << *ptr; // prints "5" (ptr has changed to point to something else
}
|
See? Exactly the same.
Why this is tricky is because while you can't modify the
pointer when it's passed by value... you
can modify whatever the pointer points to. So in a way... passing a value through a pointer is similar to passing it by reference.
But I'll spare an example here since it's unrelated to your problem at hand.