简体   繁体   中英

The following code for palindrome doesn't work?is there a logical mistake?

Could someone point me to the error in this code. Iam using codingblocks IDE.

#include <stdio.h>
main()
{
    char a[100],b[100];int i,j=0; 
    scanf("%s",&a);
    for(i=strlen(a)-1,j=0;i>=0;i--)
    {
        b[j]=a[i];
        j=j+1;
    }
    b[j]='\0';
    if(a==b) # on printing i get both 'a' and 'b' as equal however this condition still remains
             # false

        printf("true"); #doesnot print?

}

Few issues in your code

  • You never copy anything in b , so that array has random characters.

  • a==b will always be false because they are character arrays not pointers and both contain different values.

  • If you are reading string, you don't need & for char array, so the scanf() should be scanf("%s",a);

Change this statement

if(a==b)

to

if ( strcmp( a, b ) == 0 )

Otherwise you are comparing addresses of the first elements of the arrays.

Also you need to include header <string.h> . Function main shall have return type int . Change this statement

scanf("%s",&a);

to

scanf( "%s", a);

Take into account that there is no need to define second array that to determine whether a string is a palindrome. You could do this check "in place".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM