Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the length of an array which contains an element 0 while passing to a function

Tags:

c++

Is there any way to print length of an array which contains an element 0 and that array has been passed to a function which can have only one argument as the array?

Example:

int arrLen(int arr[])
{
    //get size here;
}

int main()
{
    int arr[]={0,1,2,3,4,5};
    arrLen(arr);
}

There is a limitation in C++ that we can not compare the elements of an array with a NULL if it has a zero, but still asking if there is a way to do that. I can only pass array to function is my limitation.

like image 659
Katin Marish Avatar asked Dec 08 '22 09:12

Katin Marish


1 Answers

In your very example, you can use function template to get what you want:

template <size_t N>
int arrLen(int (&arr)[N])
{
    return N;
}
like image 168
PiotrNycz Avatar answered Dec 11 '22 00:12

PiotrNycz