Hard Rain
Hard Rain

Reputation: 1410

How to get the length of an array in c++?

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

Answers (2)

David G
David G

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

juanchopanza
juanchopanza

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

Related Questions