This piece of code works fine. But I'm wondering if it can be done in a more efficient way?
More specifically this part *(s1 + i)
if it possible to force it to sequence through entire array character by character via pointer for example *s1++
.
My task to do this function compareStrings without index array [].
int compareStrings(const char *s1, const char *s2)
{
int i = 0, answer;
// i - to sequence through array of characters
// pointer to character string1 and character string2
while (*(s1 + i) == *s2 + i && *(s1 + i) != '\0'&& *(s2 + i) != '\0')
{
i++;
}
if ( *(s1 + i) < *(s2 + i) )
answer = -1; /* s1 < s2 */
else if ( *(s1 + i) == *(s2 + i) )
answer = 0; /* s1 == s2 */
else
answer = 1; /* s1 > s2 */
return answer;
But I want to change it to s1++
and s2++
insted of *(s1 + i)
and *(s2 + i)
. I've tried to implement this idea with pining an extra pointer to the beginning but I've failed. Here the code -->
int compareStrings(const char *s1, const char *s2)
{
int answer;
char **i = s1, **j = s2;
// i and j - to sequence through array of characters
while (*(i++) == *(j++) && *(i++) != '\0'&& *(j++) != '\0');
if (*i < *j)
answer = -1; /* s1 < s2 */
else if (*i == *j)
answer = 0; /* s1 == s2 */
else
answer = 1; /* s1 > s2 */
return answer;
}