On 2007-08-14 09:15, arnuld wrote:
> this programme gives unusual output. i am not able to find out where the
> semantic bug lies:
>
>
> /* C++ Primer - 4/e
> *
> * an example from section section 7.2.4, page 241 * STATEMENT
> * write a function that prints the elements of an array. don't use
> pointer to an array as parameter because pointer will be copied, use
> reference to the array instead.
> *
> */
>
>
> #include <iostream>
>
>
> /* prints the elements of an array. i could have used subscripting but the
> point here is the understanding of pointers and references */
I'm not so sure about that, since you are passing an array, not a
pointer to the first element, you know the number of elements in the
array, so a for-loop would be perfect.
> void print_array( int (&arr)[3], const size_t arr_size ) {
You know that there there are 3 elements and the function is hard-coded
for such arrays, no need for the second argument.
> int* pbegin = arr;
> int* pend = pbegin + arr_size;
>
> while( pbegin != pend)
> {
> std::cout << *pbegin++ << std::endl;
> }
Could be replaced with
for (size_t i = 0; i < 3; ++i)
{
std::cout << arr[i] << std::endl;
}
> }
>
>
> int main()
>
> {
> const size_t arr_size = 3;
Drop this, or use it to set the size of the array.
> int arr_3[3] = {10, 20, 30};
>
> print_array( (&arr_3)[3], arr_size);
I'm not really sure, but I think this passes the address of the fourth
element, not the array. When passing an array by reference you do it
just like any other variable you pass by reference, with its name:
print_array(arr_3);
--
Erik Wikström