bool pointer

Hey I am trying to write a function that returns true if two c strings are the same, but it keeps returning false.
1
2
3
4
5
6
7
8
9
10
11
12
 bool strequal(const char str1[], const char str2[])
    {
		
        while (str1 != 0  &&  str2 != 0)
        {
            if (*str1 != *str2)  // compare corresponding characters
                return false;
            str1++;          
	    str2++;				// advance to the next character
        }
        return (str1 == str2);   // both ended at same time
    }
Do your strings necessarily end with 0? Why aren't you using null?
This expression

while (str1 != 0 && str2 != 0)

is always true if only you passed str1 or str2 as NULL. So your loop will be executed until *str1 will not be equal *str2.:)
I changed the while loop to while (*str1 != '\0' && *str2 != '\0') and bool strequal(const char* str1, const char* str2)
But its still false. I dont think the loop is working right
Last edited on
You shall also change the statement

return (str1 == str2); // both ended at same time

because the value of str1 is not equal to value of str2 if only the two arrays coinside.
Last edited on
Should i just change it to return true?
But How can i test when the array has ended? It seems *str1 != '\0' does not work as intended
Last edited on
Your function can be written simpler

1
2
3
4
5
6
bool strequal( const char str1[], const char str2[] )
{
        while ( *str1 && *str1 == *str2 ) str1++, str2++;

        return ( *str1 == *str2 );   // both ended at same time
} 





wow how can i not think of that... thanks
Mark the post as resolved.:)
Topic archived. No new replies allowed.