The match function is supposed to return true if and only if its two C-string ar
ID: 3836437 • Letter: T
Question
The match function is supposed to return true if and only if its two C-string arguments have exactly same text. 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 equal
bool 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 character
str2++;
}
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;
}
}
Explanation / Answer
Hi, Please find my explanation and fixed code.
0 and '' are two different characters
and C-string end mark is : ''
So,instead of : while (str1 != 0 && str2 != 0)
It should be : while (*str1 != '' && *str2 != '')
this lien: str1 == str2 => compares the address of both string they point to,
Here we have to check whether both str1 and str2 pointing to '' character, so
it should be :
*str1 == *str2
Like this : str1 != str2
should be also: *str1 != *str2
####################################
#include <iostream>
using namespace std;
// return true if two C strings are equal
bool match(const char str1[], const char str2[])
{
bool result = true;
while (*str1 != '' && *str2 != '') // zero bytes at ends
{
if (*str1 != *str2) // compare corresponding characters
{
result = false;
break;
}
str1++; // advance to the next character
str2++;
}
if (result)
{
result = (*str1 == *str2); // both ended at same time?
}
return( result );
}
int main()
{
char a[10] = "pointy";
char b[10] = "pointy";
if (match(a,b))
{
cout << "They're the same!" << endl;
}else{
cout << "They are not same!" << endl;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.