strcmp在这个程序中有什么问题?

时间:2012-11-30 19:11:12

标签: c strcmp

当我运行程序并回答“是”时,它告诉我我错了。有人知道执行这种程序的方法吗?

#include <string.h>
#include <stdio.h>
int strcmp(const char *str1,const char *str2 );

// I am trying to make a program that asks the user to input an answer 
int main() 
{
    char answer[20];


    printf("Can birds fly?\n");   
    scanf("%s", &answer[20]);    


    if(strcmp(answer, "yes") == 0)  
    {
        printf("You are right"); 
    }else
    {
        printf("You are worng"); 
    }

    return 0; 
}

1 个答案:

答案 0 :(得分:5)

更改此行:

scanf("%s", &answer[20]); 

为:

scanf("%s", answer);

您必须将scanf传递给要放置字符串的地址,answer[20]选择字符串中第21个字符的值(未定义,因为字符串仅为20个字符)然后指向它(垃圾,你甚至可能会遇到访问冲突)。