Technologies Ignited

Technologies Ignited

How to get the length of an array?

leave a comment »

Do you know we’ve moved on a new address. There will be no new articles on this blog anymore. If you still want to keep in touch with us, follow us @ Code Mamba!You can read the same article on our new domain by clicking here!
In C++ you can get the length of an array by calculating it:

int sz = sizeof(arr) / sizeof(arr[0]);

This takes the memory, used for your array and divides it by the size of the elements inside.
However there’s also another better(sometimes) solution. All you need to do is to create a template function:

template<typename T, size_t N>
int length(const T (&)[N])
{
    return N;
}

Here’s how to use this:

int main()
{
    int arr1[] = {1,2,3,4,5,6,7};
    double arr2[] = {1.1,2.2};
    char *arr3[] = {"el", "em", "en", "ts"};
    
    printf
    (
        "arr 1: %d\narr 2: %d\narr 3: %d\n",
        length(arr1),
        length(arr2),
        length(arr3)
    );
    
    system("pause");
    return 0;
}

The output should look like this:
How to get the length of an array

Written by wyand

15 August 2011 at 16:04

Posted in C++

Tagged with ,

Leave a comment