Answer to Question #267536 in C++ for malika

Question #267536

The strequal 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 strequal(const char str1[], const char str2[])
    {
        while (str1 != 0  &&  str2 != 0)  // zero bytes at ends
        {
            if (str1 != str2)  // compare corresponding characters
                return false;
            str1++;            // advance to the next character
            str2++;
        }
        return str1 == str2;   // both ended at same time?
    }

    int main()
    {
        char a[15] = "Wang, A.";
        char b[15] = "Wang, R.";

        if (strequal(a,b))
            cout << "They're the same person!\n";
    }
1
Expert's answer
2021-11-18T15:16:47-0500
#include <iostream>


using namespace std;


// return true if two C strings are equal
bool strequal(char str1[], char str2[])
{
   char *st1 = str1, *st2 = str2;
   while (*st1 != 0 && *st2 != 0) // zero bytes at ends
   {
      if (*st1 != *st2) // compare corresponding characters
         return false;
      st1++; // advance to the next character
      st2++;
   }
   return true; // both ended at same time?
}


int main()
{
   char a[15] = "Wang, R.";
   char b[15] = "Wang, R.";


    if (strequal(a, b))
        cout << "They're the same person!\n";
    else
        cout << "They're not the same person\n";
      
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS