Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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;
}
like image 828
Hard Rain Avatar asked Nov 17 '25 12:11

Hard Rain


1 Answers

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";
like image 131
juanchopanza Avatar answered Nov 20 '25 05:11

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!