gpt4 book ai didi

c - 为什么下面代码的输出是 "not found"而不是 "found"?

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

下面的代码给出了“未找到”的输出。但我希望它能给出“发现”。我的错误在哪里?

#include <stdio.h>

void compare(char *x, char *face);
int i;

int main(void){

char array[5]="Two";
char *numbers[4]={"One", "Two", "Three", "Four"};

compare(array, *numbers);

}

void compare(char *x, char *y){

for (i = 0; i < 4; i++)
{
if (*x==y[i])
{
printf("\n found");
return;
}

}
printf("\n not found\n");
}

最佳答案

*x==y[i] 中,您比较的是两个字符的值,而不是两个指针指向的数据。使用 strcmp代替功能。如果给定的两个指针指向的两个字符串相等,则返回 0。所以将其更改为 strcmp(x, y[i]) == 0

您还应该将 char *y 参数更改为 char **ychar *y[] 因为 y 是一个数组指向字符串的指针,而不仅仅是一个指针。

最后,compare(array, *numbers); 应该被调用为 compare(array, numbers); 因为你想传递一个指向字符串数组的指针,不仅仅是一个指向一个字符串的指针(numberschar*[4] 类型,但它会在传递时衰减为 char** 类型作为论据)。

关于c - 为什么下面代码的输出是 "not found"而不是 "found"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17545772/

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