Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the length of an array?

Tags:

c++

arrays

Is there a way to find how many values an array has? Detecting whether or not I've reached the end of an array would also work.

like image 802
Maxpm Avatar asked Nov 05 '10 17:11

Maxpm


People also ask

What is the length of the array?

Basically, the length of an array is the total number of the elements which is contained by all the dimensions of that array. Property Value: This property returns the total number of elements in all the dimensions of the Array. It can also return zero if there are no elements in the array.

How do you find the length of an array in Java?

To get the size of a Java array, you use the length property. To get the size of an ArrayList, you use the size() method. Know the difference between the Java array length and the String's length() method.


2 Answers

If you mean a C-style array, then you can do something like:

int a[7]; std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl; 

This doesn't work on pointers (i.e. it won't work for either of the following):

int *p = new int[7]; std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl; 

or:

void func(int *p) {     std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl; }  int a[7]; func(a); 

In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector.

like image 188
Oliver Charlesworth Avatar answered Oct 17 '22 02:10

Oliver Charlesworth


As others have said, you can use the sizeof(arr)/sizeof(*arr), but this will give you the wrong answer for pointer types that aren't arrays.

template<class T, size_t N> constexpr size_t size(T (&)[N]) { return N; } 

This has the nice property of failing to compile for non-array types (Visual Studio has _countof which does this). The constexpr makes this a compile time expression so it doesn't have any drawbacks over the macro (at least none I know of).

You can also consider using std::array from C++11, which exposes its length with no overhead over a native C array.

C++17 has std::size() in the <iterator> header which does the same and works for STL containers too (thanks to @Jon C).

like image 42
Motti Avatar answered Oct 17 '22 01:10

Motti