Hi everyone! I am trying to write a function that compares the original word with its reversed. My main problem, and I cannot figure out why, I am getting always a "false" return in a boolean function that compares the two words. I have checked for spaces or strange word composition but it seems all ok. Here is my code:
Code:
int len(const char* s)
{
int n = 0;
while (*s != '\0')
{
++n;
++s;
}
return n;
}
char* reverse_word(const char* c)
{
int n = len(c);
// char* p2 = new char[n + 1];
// char* temp = &p2[n];
char* p2 = new char[n + 1](); // *** default initialize
char* temp = &p2[n - 1]; // ***
while(*c != '\0') *temp-- = *c++;
delete[] p2;
return p2;
}
bool is_palindrome(const char* c, const char* p)
{
if (p == c) return true;
return false;
}
int main(int argc, const char * argv[])
{
char ar[] = {"kayak"};
char* p = &ar[0];
char* p1 = nullptr;
p1 = reverse_word(p);
cout << p << " and " << p1 << " are ";
if (!is_palindrome(p,p1)) cout << "not ";
cout << "palindromes." << endl;
keep_window_open();
return 0;
}
Thank you very much