Reputation: 1825
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?
Upvotes: 2
Views: 98
Reputation: 311038
Just declare the parameter as having a referenced type.
For example
template<class T>
void foo( const T &ar )
{
size_t n = sizeof(ar) / sizeof(ar[0]);
std::cout << n << std::endl;
for (int i = 0; i < n; i++)
std::cout << ar[i] << " ";
}
Or you may use the following declaration
template<class T, size_t N>
void foo( const T ( &ar )[N] )
{
std::cout << N << std::endl;
for (int i = 0; i < N; i++)
std::cout << ar[i] << " ";
}
Otherwise the function deals with a pointer. In this case you need specify a second parameter that denotes the length of the array like
template<class T>
void foo( const T* ar, size_t n )
{
std::cout << n << std::endl;
for (int i = 0; i < n; i++)
std::cout << ar[i] << " ";
}
As the passed array is not being changed in the function then the corresponding parameter should have the qualifier const
.
Pay attention to that in the C++ 17 Standard there is introduced standard function std::size
declared in the header <iterator>
that can be used
instead of the expression sizeof(ar) / sizeof(ar[0])
So you could write for example in the first shown function
size_t n = std::size(ar)`;
Upvotes: 3