Advertisement
Advertisement


How do I find the length of an array?


Question

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.

2011/11/30
1
557
11/30/2011 1:20:01 PM

Accepted Answer

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.

2019/11/16
523
11/16/2019 8:11:48 AM

As other's 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).

2018/07/16

Doing sizeof( myArray ) will get you the total number of bytes allocated for that array. You can then find out the number of elements in the array by dividing by the size of one element in the array: sizeof( myArray[0] )

2010/11/05

While this is an old question, it's worth updating the answer to C++17. In the standard library there is now the templated function std::size(), which returns the number of elements in both a std container or a C-style array. For example:

#include <iterator>

uint32_t data[] = {10, 20, 30, 40};
auto dataSize = std::size(data);
// dataSize == 4
2018/02/02

Is there a way to find how many values an array has?

Yes!

Try sizeof(array)/sizeof(array[0])

Detecting whether or not I've reached the end of an array would also work.

I dont see any way for this unless your array is an array of characters (i.e string).

P.S : In C++ always use std::vector. There are several inbuilt functions and an extended functionality.

2010/11/05

std::vector has a method size() which returns the number of elements in the vector.

(Yes, this is tongue-in-cheek answer)

2010/11/05

Source: https://stackoverflow.com/questions/4108313
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]