以下的回文代码不起作用?是否存在逻辑错误?

时间:2014-12-07 13:05:42

标签: c logic palindrome

有人能指出我这段代码中的错误。我使用的是编码块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?

}

2 个答案:

答案 0 :(得分:1)

您的代码中存在少量问题

  • 您永远不会复制b中的任何内容,以便该数组包含随机字符。

  • a==b将始终为false,因为它们是字符数组而不是指针,并且都包含不同的值。

  • 如果您正在阅读字符串,那么char数组不需要&,因此scanf()应为scanf("%s",a);

答案 1 :(得分:1)

更改此声明

if(a==b)

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

否则,您要比较数组的第一个元素的地址。

您还需要包含标题<string.h>。函数main应具有返回类型int。更改此声明

scanf("%s",&a);

scanf( "%s", a);

考虑到没有必要定义第二个数组来确定字符串是否是回文。你可以检查&#34;到位&#34;。