Nanton Zhang Nanton Zhang - 10 days ago 8
C Question

What does `return 1 + strlen_rec(&arr[1]) ;` mean?

I have some code:

int strlen_rec(char arr[])
{

if(arr[0]=='\0')
return 0;
else
return 1 + strlen_rec(&arr[1]) ;
}


The line

return 1 + strlen_rec(&arr[1]) ;


is confusing me. Can someone explain what it does?

Answer

This function counts the length of a string using recursion. It may look confusing since it's using an array like a pointer. &ar[1] is increasing the pointer (calling the function with the address of the next byte). C strings are terminated with a null byte which isn't included in the length so it returns 0 when reached.