Component parts of program work, when put together does not work
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;
}
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.
精彩评论