1

I'm trying to create a function which determines length of Array. My code doesn't work, please HELP!

#include <iostream>

using namespace std;

  int ArrayLength(int Array[])
    {
        int i = 0;
        while (Array[i] != NULL)
        {
            i++;
        }
        return i;
    }

int main(void)
{
    int test[5] = { 4,5,6,7,1 };
    int testLen = ArrayLength(test);
    cout << " test length  = " << testLen;

    return 0;
}

3 Answers3

2

An array is not NULL terminated, so you cannot assume that there is an end element equal to NULL. When an array is passed to your function ArrayLength(), it's decayed to a pointer to the first array element with all information about the size of the array lost.

In order to get the size of an array (not a pointer pointing to its first element) in bytes, use the sizeof() operator.

int array[5] = {0,1,2,3,4};
static_assert(sizeof(array) == 5*sizeof(int),"!!");

If you want a function to take array as argument and return its size, you can construct a template:

template<typename T, size_t N>
size_t ArrayLength(const T& [N])
{ return N; }
Walter
  • 44,150
  • 20
  • 113
  • 196
2

When an array is passed by value it is implicitly converted to pointer to its first element. Moreover arrays do not have a sentinel value.

The function can be declared like

template <size_t N>
constexpr size_t ArrayLength(const int(&a)[N])
{
    return N;
}

Or like

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

Take into account that there is standard C++ class std::extent declared in header <type_traits> that does the task.

For example

#include <iostream>
#include <type_traits>

int main()
{
    int test[5] = { 4,5,6,7,1 };

    std::cout << std::extent<decltype(test)>() << std::endl;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You can find length of array using this

int testLen = (sizeof(test)/sizeof(*test));

Hope this helps !

zenwraight
  • 2,002
  • 1
  • 10
  • 14