Search code examples
c++functioncompiler-constructionreversepalindrome

How to call a function within a function?


I am trying to determine if my code is a palindrome so I created a reverse function and then a palindrome function. I am trying to assign the reversed Character array into the new function but I can't seem to get it to compile.... any tips? Here is my palindrome function

bool Palindrome(char Characters[], unsigned long length)
{
   char tempstring[62];
   tempstring[62] == reverse(Characters);

   for(int i=0; i <= length; i++){
      if(Characters[i] == tempstring[i])
          return false;
      else
          return true;
   }

}

Here is my reverse function

void reverse(char Characters[], unsigned long length)
{
    char temp;   

    for(int i=0; i<length/2; i++){
        temp = Characters[i];
        Characters[i]=Characters[length-i-1];
        Characters[length-i-1]=temp;

    }
}

Solution

  • You are making this quite complicated.

    Just find the end of the string (strlen). Read from both ends a character at a time and if they do not match then it is not a palindrome. If the indexes become the same or they cross then you are done. It is indeed a palindrome.

    I.e

    bool Palindrome(char *s) {
       int left = 0, right = strlen(s) - 1;
       while (left < right) {
          if (s[left] != s[right] return false;
          ++left;
          --right;
       }
       return true;
    }
    

    EDIT

    Similar vain to construct the reverse

    char *Reverse(char *s)
    {
        char *rev = new char[strlen(s) + 1];
        int left = 0, right = strlen(s) - 1;
        while (right > -1) {
           rev[left] = s[right];
           right--;
           left++;
        }
        rev[left] = 0;
        // Remember to use delete[]
        return rev;
     }
    

    EDIT 2

    Or

    void Reverse(char[] s, int len) {
       int left = 0; right = len;
       while (right > -1) {
          char t = s[left];
          s[left] = s[right];
          s[right] = t;
          left++; right--;
       }
    }
    

    Then make a copy of the string, reverse it and compare it.