Hello, I am writing my own string library as sort of an exercise and I am doing rarther well so far. I am a bit stuck on a function which locates the occurance of a substring within a larger string. Here is my function:
int locate_substring_occurrence(string_c s_stringToSearch, string_uc s_substring, int i_occurrenceNumber)
{
int i_substringLength = (sizeof(s_substring) / sizeof(constchar)) - 1;
int i_substringSearchPosition = 0;
for(int i = 0; i < 16384; i ++)
{
if(s_substring[i_substringSearchPosition] == s_stringToSearch[i])
{
if(i_substringSearchPosition < i_substringLength)
{
i_substringSearchPosition ++;
}
else
{
return i - i_substringLength;
}
}
}
return -1;
}
(Ignore parameter 3, its not used at the moment) Now, it appears to work fine with substrings over 3 characters long, if I test it with locate_substring_occurrence("hojocina eliphaa deaketyed cib tiuzi", "deaketyed", 1) I get an output of 17 as expected, but if I try it with the substring as "cib" I get an output of 33. I have no idea why substrings less than 4 characters long yield incorrect results. I have tried re-arranging the code and I pretended to be a compiler myself and wrote the results down on a piece of paper but I still couldent figure out why I was getting this error. Btw, string_c and string_uc are typedefs;
int i_substringLength = (sizeof(s_substring) / sizeof(constchar)) - 1;
This will not give you the length of the string. s_substring is a pointer so sizeof(s_substring) gives you the size of a pointer.