So, I'm reading Stephen Prata's C++ Primer Plus. I'm on the Chapter 7 which deals with functions. One of the chapter review questions is this: Write a function that takes 3 arguments: A pointer to the first element of a range in an array, a pointer to the element following the end of the range of the array, and an int value. Have the function set each element of the array to the int value. Here was what I wrote:
1 2 3 4 5
void set_array (int * pb; int * pe; int value)
{
for (int * pt = pb; pt != pe; pt++)
*pt = value;
}
However, the answer given at the back of the book is this:
1 2 3 4 5
void set_array (int * pb; int * pe; int value)
{
for (int * pt = pb; pt != pe; pt++)
pt* = value;
}
Basically the answer is putting the dereference operator AFTER the pointer, which I don't understand why. I always thought you put it BEFORE the pointer variable. Am I right? Wrong? If I am wrong, why?
Both versions are wrong, as the parameters should be separated by commas, not semi-colons.
You are correct regarding the dereferencing of the pointer.
Finally, I'd recommend the use of < rather than !=, to avoid a loop which may never terminate. If the user calls the function with pb > pe, the loop won't end, and an exception will occur (program crash).
My recommendation:
1 2 3 4 5
void set_array (int * pb, int * pe, int value)
{
while (pb < pe)
*pb++ = value;
}