155k views
4 votes
Explain what the problems with the implementation of the function are, and show a way to fix them.// return true if two C strings are equalbool match(const char str1[], const char str2[]){bool result = true;while (str1 != 0 && str2 != 0) // zero bytes at ends{if (str1 != str2) // compare corresponding characters{result = false;break;}str1++; // advance to the next characterstr2++;}if (result) {result = (str1 == str2); // both ended at same time?}return( result );}int main(){char a[10] = "pointy";char b[10] = "pointless";if (match(a,b)){cout << "They're the same!" << endl;}}

User Nlowe
by
4.7k points

1 Answer

2 votes

Answer:

The code is not dereferencing the pointers. You have to place an asterisk in front of the pointer to read the value the pointer points to.

Step-by-step explanation:

So "if (str1 != str2)" must be "if (*str1 != *str2)".

likewise:

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

and

result = (*str1 == *str2);

User Smatyas
by
4.8k points