3

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;
}
Hard Rain
  • 1,380
  • 4
  • 14
  • 19
  • 1
    https://gist.github.com/3959946 see last function. – R. Martinho Fernandes Nov 24 '12 at 15:33
  • http://stackoverflow.com/questions/3368883/how-does-this-size-of-array-template-function-work – relaxxx Nov 24 '12 at 15:33
  • 1
    @R.MartinhoFernandes: That function will give the size at runtime even though the compiler knows size at compile-time itself. Therefore, I wouldn't say that is a good implementation. – Nawaz Nov 24 '12 at 15:36
  • He only wants the array length at runtime. – Puppy Nov 24 '12 at 15:45
  • The answers so far posted here only work for arrays whose size is known at compile time. AFAIK there is no portable way to find out the length of a dynamically allocated array (safe for remembering it yourself). – Cubic Nov 24 '12 at 15:50
  • Is this the proper time to recommend `std::vector`, which knows its own size? – Bo Persson Nov 24 '12 at 16:42
  • @BoPersson That's a good recommendation. Since OP is dealing with fixed size arrays, maybe `std::array` or `std::tr1::array` might be a better fit. – juanchopanza Nov 25 '12 at 08:42
  • @DeadMG He didn't say that anywhere and giving a compile-time solution is always better than a runtime solution for obvious reasons. – legends2k Oct 12 '13 at 08:30

2 Answers2

6

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";
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

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.

David G
  • 94,763
  • 41
  • 167
  • 253