Reputation: 561
A simple program, a static string which is used to read the input, then pass it to the function. Just wondering why it can not find the '\0' character using the while(*string!='\0') expression.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int is_palindrome(char *string)
{
int length, mid, end, i;
length=0;
if (string == NULL)
return 0;
while (string[length] != '\0')
{
printf("%c\n", string[length]);
length++;
}
//Not working version
/*
while(*string!='\0')
length++;
*/
end = length - 1;
mid = length / 2;
printf(" end=%d, mid=%d\n", end, mid);
for (i = 0; i < mid; i++) {
if (string[i] != string[end]) {
printf("It's not palindrome\n");
return 0;
}
end--;
}
if (i == mid) {
printf("It's palindrome\n");
return 1;
}
return 0;
}
int main(void)
{
char string[100];
printf("Enter a string to test for the parlindrome\n");
gets(string);
int length = strlen(string);
printf("You entered %s,length is %d\n", string, length);
if (is_palindrome(string))
;
printf("Enter to Quit\n");
char x;
scanf("%c", &x);
return 0;
}
Upvotes: 0
Views: 173
Reputation: 19494
Initialize length
to 0 before using its value in the while
loop.
Or you could use the standard library function strlen()
.
Also, in the palindrome check, you should probably decrease end
at the same you increase i
. As it is, you're comparing the characters in the first half each with the same char at the end. This will match strings like "aaaabfa" but not "abcdcba".
Upvotes: 1
Reputation: 36082
Instead of
while(*string!='\0')
length++;
write
char* p = string;
while( *p++ )
length++;
otherwise the pointer will not move and you become stuck in an infinite loop (if the string is not empty). Use p
to avoid changing the original pointer.
Also initialize all variables before using them, good rule of thumb.
Upvotes: 3