tags:

views:

51

answers:

1

I'm trying to complete the Project Euler problem found here. For some reason my function that determines whether or not a given string is a palindrome thinks "989010" is a palindrome. The funny thing is, if I directly enter that string into the palindrome function, it functions correctly. Here's my code (I'm a newb so sorry for the bad formatting!):

bool palindrome(char pal[]);

int main(){
int i = 0;
int j = 0;
int k = 0;
int numdig = 0;
int numtest = 0;

 for(i = 999; i > 99; i--){
  for(j = 999;j > 99; j--){  //for loops multiply all 3 digit numbers
   k = i * j;
   numtest = k;
   numdig = 0; //this part takes care of determining the number of digits
    while(numtest > 0){
    numdig++;
    numtest /= 10;
    }
   char string[numdig + 1];
   itoa (k,string,10);  //itoa turns an integer into a string w/ null char.
                if( palindrome(string)){
     printf("It is a palindrome: %i\n",k);
     system("pause");
     return 0;
    }
  }
 }
 return 0; 
}

    bool palindrome(char pal[]){
 int half = (sizeof(pal) - 1)/2; //this divides the string in half
 int forward = 0;                 
 int backward = sizeof(pal)-2;   

    while(forward < half && backward > 0){  //compares the charactera in the front 
  if(pal[forward] == pal[backward]){  //to the chars in the back until they
   forward++;                      //meet in the middle
   backward--;
  }
        else{
   return false;
        }
 }
 return true;
}
+4  A: 

The sizeof of the parameter is not the character count of the string pointed to, because the parameter, despite its declaration form, is merely a pointer but not an array. Use strlen instead and notice that it does not include the terminating \0 in its returned value (as opposed to sizeof when applied to a string array).

The string "989010" looks like a palindrome if you only take the first 3 characters of it, "989". Since sizeof applied to a pointer yields 4 on your machine, it's only those first three characters that are inspected.

Johannes Schaub - litb
`backward` does however need to be initialised to `strlen(pal) - 1`, so that it starts at the last character in the string.
caf
@caf, good point. I made my statement more general to cover that too.
Johannes Schaub - litb
Wow, thanks! It works perfectly now, great advice. I am a little confused at what I was doing wrong though. Could you please shed a little bit more light on what I did wrong?
Brian
@Brian for performance reasons, you cannot pass arrays by value. Instead, passing an array will always get a pointer to its first element passed. Consequently, there are no array type parameters. When you declare a parameter to be an array, it's not really an array. Any size information in the parameter declaration (if present) is ignored, and the parameter becomes a pointer. Thus, your parameter really is a `char *`.
Johannes Schaub - litb