cstringrecursiondynamicpalindrome

Check if a string is palindrome in C


i've a question about this code i'm writing for an exercise. I've to check if a string is palindrome. I can't change the declaration of the function.The function only return 1 when all the letters are the same (like "aaaa") but if i charge the sentence with other palindrome (like "anna") the function return me 0 , i can't figure out why this appening.Thank you!

char* cargar (char*);
int pali (char*);

int main()
{ 
   char*texto=NULL;
   texto=cargar(texto);
   int res=pali(texto);
   if(res==1){printf("\nPalindrome");}
   else printf("\nNot palindrome");

   return 0;
}

char* cargar (char*texto)
{
   char letra;
   int i=0;
   texto=malloc(sizeof(char));
   letra=getche();
   *(texto+i)=letra;
   while(letra!='\r'){
      i++;
      texto=realloc(texto,(i+1)*sizeof(char));
      letra=getche();
      *(texto+i)=letra;}
   *(texto+i)='\0';      
   return texto;
}

int pali (char* texto)
{
   int i;
   for(i=0;*(texto+i)!='\0';i++){
   }i--;
   if(i==0||i==1){return 1;}

   if(*texto==*(texto+i)){
      return pali(++texto);
   }
   else return 0;
}

Solution

  • Your function to determine whether a string is a palindrome is not well thought out.

    Let's say you have a string s of length l. The characters in the string are laid out as:

    Indices: 0    1    2    3            l-4  l-3  l-2  l-1
             +----+----+----+----+- ... -+----+----+----+----+
             |    |    |    |    |  ...  |    |    |    |    |   
             +----+----+----+----+- ... -+----+----+----+----+
    

    If the string is a palindrome,

    s[0] = s[l-1]
    s[1] = s[l-2]
    
    ...
    

    You can stop checking when the index of the LHS is greater or equal to the index of the RHS.

    To translate that into code,

    int is_palindrome(char const* s)
    {
       size_t len = strlen(s);
       if ( len == 0 ) // An empty string a palindrome
       {
          return 1;
       }
    
       size_t i = 0;
       size_t j = len-1;
       for ( ; i < j; ++i, --j )
       {
          if ( s[i] != s[j] )
          {
             // the string is not a palindrome.
             return 0;
          }
       }
    
       // If we don't return from inside the for loop,
       // the string is a palindrome.
       return 1;
    }