On Tue, 14 Aug 2007 07:47:13 +0000, Erik Wikström wrote:
Quote:
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.
i know but it produces error:
for( int* pbegin = arr, pend = pbegin + arr_size;
pbegin != pend; ++pbegin)
{
std::cout << *pbegin++ << std::endl;
}
7.2.4_print-array.cpp: In function 'void print_array(int (&)[3],
size_t)': 7.2.4_print-array.cpp:23: error: invalid conversion from
'int*' to 'int'
7.2.4_print-array.cpp:23: error: ISO C++ forbids comparison between
pointer and integer
i did not understand why it was taking "pend" as integer. and page 117 of
C++ Primer says: i am stupid because i wrote that: "int* pbegin, pend"
thing and expected both of them to be a pointer, in fact they are 2
different types"
Quote:
Quote:
>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.
actually, i wanted it to be like this: "int (&arr)[]" but that is
compile time error :(
7.2.4_print-array.cpp:18: error: parameter 'arr' includes reference
to array of unknown bound 'int []'
Quote:
for (size_t i = 0; i < 3; ++i)
{
std::cout << arr[i] << std::endl;
}
yes, it is easy and the author wants me to use pointers, arrays and
references.
Quote:
Quote:
> print_array( (&arr_3)[3], arr_size);
Quote:
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);
and i was passing, print_array(&arr_3[]), heck....references always
confuse me.
BTW, here is the new code, compiles and runs fine and th eonly thing i
wanted to implement was passing a reference to an array of unknown array
(Aye.. do i need Dynamic Array for this ?)
/* 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 as parameter.
*
*/
#include <iostream>
/* prints the elements of an array. i could have used subscripting but the
point here is the understanding of pointers and references */
void print_array( int (&arr)[3], const size_t arr_size ) {
for( int *pbegin = arr, *pend = pbegin + arr_size; pbegin != pend;
++pbegin)
{
std::cout << *pbegin << std::endl;
}
}
int main()
{
const size_t arr_size = 3;
int arr_3[arr_size] = {10, 20, 30};
print_array( arr_3, arr_size);
return 0;
}
/* OUTPUT
~/programming/cpp $ g++ -ansi -pedantic -Wall -Wextra
7.2.4_print-array.cpp ~/programming/cpp $ ./a.out
10
20
30
~/programming/cpp $
*/
--
http://arnuld.blogspot.com