gpt4 book ai didi

C: strcmp 错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:55:46 24 4
gpt4 key购买 nike

我有两个字符串要比较以检查它们是否相同并且它有效但是当我今天打开项目时它让我感到错误。

warning C4047: 'function' : 'const char *' differs in levels of indirection from 'char (*)[5]'
warning C4024: 'strcmp' : different types for formal and actual parameter 1
warning C4047: 'function' : 'const char *' differs in levels of indirection from 'char (*)[5]'
warning C4024: 'strcmp' : different types for formal and actual parameter 1

printf("Your answer: ");
scanf_s("%s", &answer, 5);
//strlwr(answer);
_strlwr(answer);
if ((strcmp(&answer, "ja") && location[question].rightAnswer == 1) || (strcmp(&answer, "nej") && location[question].rightAnswer == 0) || (strcmp(&answer, "yes") && location[question].rightAnswer == 1) || (strcmp(&answer, "no") && location[question].rightAnswer == 0)){
printf("Right answer!\n\n");
points += difficulty;
}
else if ((strcmp(&answer, "ja") && location[question].rightAnswer != 1) || (strcmp(&answer, "nej") && location[question].rightAnswer != 0)){
printf("Wrong answer!\n\n");
}
else{
printf("Don't understand your input\n");
}

最佳答案

strcmp接受两个 const char* 并且对于第二个参数你传递 "ja" 这是正确的,而对于第一个参数,你传递指向数组的指针5 个 char,这就是您在编译器错误中看到 char (*) [5] 的原因。修复它是为了做

strcmp(answer, "ja");    // & operator NOT applied to answer

执行此操作时,数组衰减将启动,类型为 char [5]answer 将变为 char* a char指向数组第一个元素的指针。

当您应用 & 运算符时,您会得到一个指向数组本身的指针,而不是衰减行为。这是少数不会发生腐烂的地方之一。另外两个是 sizeof 和字符串文字初始值设定项。参见 here了解详情。

关于C: strcmp 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com