Given the following function:
template<class T>
void foo(T* ar)
{
std::cout << sizeof(ar) / sizeof(ar[0]) << std::endl;
for (int i = 0; i < 6; i++)
std::cout << ar[i] << " ";
}
And following array:
int ar[] = { 5, 1, 6, 8, 9, 3 };
foo(ar);
I expected the program to print '6' and then the contents of the array. But for some reason, sizeof(ar) / sizeof(ar[0])
evaluates to 1 (since both sizeof(ar)
and sizeof(ar[0])
evaluate to '4'), but the print works fine (meaning passed array does contain all 6 elements).
This only happens to arrays passed to functions (I tried evaluating length in main(), where array was declared and it worked fine). How can I get the length of an array inside a function?
std::vector
is the preferred way of passing arraysar
decays to a pointer when passed to a function, soar
infoo
is just a pointerarray_view
, or pass array by reference, or pass size explicitly. And never ever use something likesizeof(ar) / sizeof(ar[0])
to figure out size of the array, use::std::size
instead.