my exercise is to create my own strrchr() function in c.
My solution is a loop. I'am counting the array length. I will input this number into the for loop. For example: With the input Hello. I will go from right to left to search for a letter.
What's not working is the return part.
My code returns the following with the input Hello, and search letter l. lo. That's not what I need. My ouput should be lleH.
Any ideas what I did wrong?
char *KULstrrcichr(char *arr, char search)
// The strrchr() function returns a pointer to the last occurrence of the character c in the string s.
{
int stringcnt;
stringcnt = strlen(arr);
printf("%d\n", stringcnt);
search = tolower(search);
for (int i = stringcnt-1; arr[i]; i--)
{
arr[i] = tolower(arr[i]);
}
for (int i = stringcnt-1; arr[i]; i--)
{
if (search == arr[i])
{
return &arr[i];
}
}
return 0;
}
Okay I found out that my code works as expected...
The standard C function
strrchr
is declared the following wayThat is it first parameter has the qualifier
const
and the second parameter is of the typeint
. It means that you may not change the source string.Also this for loop
invokes undefined behavior due to the incorrect condition.
The function can be defined the following way as shown in the demonstration program below.
The program output is