For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
The array temp
does not contain a string because you forgot to append it with the terminating zero character '\0'.
So the call of the strcmp
if(strcmp(temp, str)==0)
results in undefined behavior.
Also the function gets
is unsafe and is not supported by the C Standard. Instead use the function fgets
.
Also to check whether a string is a palindrome there is no need to declare an auxiliary array.
The code can look like
printf("type the desired to string to check pallindrome\n");
fgets(str, sizeof( str ), stdin );
str[strcspn( str, "\n" )] = '\0'; // to remove the new line character '\n'
size_t n = strlen( str );
printf( "%zu\n", n );
size_t i = 0;
while ( i < n / 2 && str[i] == str[n-i-1] ) ++i;
if( i == n / 2 )
{
printf("pallindrome\n");
}
else
{
printf("not a pallindrome\n");
}
You could write a separate function that checks whether a string is a palindrome.
Here you are.
#include <stdio.h>
#include <string.h>
int is_palindrome( const char *s )
{
size_t n = strlen( s );
size_t i = 0;
while ( i < n / 2 && s[i] == s[n-i-1] ) ++i;
return i == n / 2;
}
int main(void)
{
enum { N = 100 };
char s[N];
printf( "Type a desired string to check whether it is a palindrome: " );
fgets( s, sizeof( s ), stdin );
s[ strcspn( s, "\n" ) ] = '\0';
if ( is_palindrome( s ) )
{
printf( "\"%s\" is a palindrome.\n", s );
}
else
{
printf( "\"%s\" is not a palindrome.\n", s );
}
return 0;
}
The program output might look like
Type a desired string to check whether it is a palindrome: abcdedcba
"abcdedcba" is a palindrome