Home > Blockchain >  C pass an array to a function without knowing its type
C pass an array to a function without knowing its type

Time:05-31

I want to make a function that takes an array as an argument with ANY type and returns its length like the following example:

unsigned int getLength(array)
{
   return sizeof(array) / sizeof(array[0])
}

I don't know if it's possible to even possible to pass an array without knowing its type, I hope I explained my question well, thank you...

CodePudding user response:

You can use templates as shown below. In particular, we can make use of template nontype parameter N to represent the length of the passed array and template type parameter T to represent the type of the element inside the array.

template<typename T, std::size_t N>
//--------------------------v--------------->type of elements inside array named arr
std::size_t getLength(const T (&arr)[N])
//-----------------------------------^------>length of the array
{
    return N ;
}

int main()
{
    int arr[] = {1,2,3};
    std::cout<<getLength(arr)<<std::endl;
    
    std::string arr2[] = {"a", "b"};
    std::cout<<getLength(arr2)<<std::endl;
    return 0;
}

Working demo


Note with C 17 there is also an option to use std::size.

  • Related