Reputation: 1410
I tried to write my own function for this, but I get wrong result
#include <iostream>
using namespace std;
template<typename T>
int array_length(T v[]) {
return (sizeof v)/sizeof(T);
}
int main() {
int v[] = {1, 2, 3, 4};
cout << array_length(v) << endl;
return 0;
}
Upvotes: 3
Views: 231
Reputation: 96810
The length is supplied by the array. So try this:
template <typename T, std::size_t N> std::size_t length( T (&)[N] ) {
return N;
}
std::size_t
is found in header <cstddef>
. It is an unsigned integer type.
Upvotes: 1
Reputation: 227420
Something like this:
#include <cstddef> // for size_t
template< typename T, std::size_t N >
std::size_t length( const T (&)[N] )
{
return N;
}
Usage
int data[100];
std::cout << length(data) << "\n";
Upvotes: 6