Friday, January 27, 2006

Found an interesting question.

given the following code:

p is not NUL terminated char array
int foo(char *p, char c, int length)
{
for(int i = 0 ; i <= length ; i++)
{
if(p[i] == c) return i;
}
return -1;
}

question:
1. what does above code do?
2. how many comparison for each iteration?
3. can you modify the function to have less comparison for each iteration?
(hint: p is not pointer to a const char)

No comments: