gpt4 book ai didi

来自两个不同数组的字符匹配,尽管它们不同

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

我已经定义了一个函数,当调用并给定两个字符串时,该函数应该检查第一个字符串的字母是否存在于第二个字符串中。这是我的代码:

int lettersOfAInB(char a[], char b[])
{
int count = 0;

for(int i = 0; a[i] !='\0'; i++)
{
count = 0;
for(int j = 0; b[j] !='\0'; j++)
{
if(a[i] == b[j])
{
count = 1;
break;
}
}
if(count == 0)
return 0;
}
return 1;
}

int main()
{
char a[5] = "zc";
char b[4] = "oabq";
int is;

is = lettersOfAInB(a, b);

if(is)
printf("Yes");

printf("\n");
return 0;
}

无论我作为参数提供的字符串如何,这将始终输出"is"。有人可以解释一下为什么吗?谢谢。

最佳答案

Could someone explain me why please?

未定义行为(UB)

for(int j = 0; b[j] !='\0'; j++) 尝试访问超过其 4 个元素的 char b[4]。结果 UB。任何事情都可能发生。


如果将其编码为将char b[] 视为字符串(具有空字符 的数组),则允许编译器需要的数组大小

// char b[4] = "oabq";
char b[] = "oabq"; // now `b[]` has 5 ellements

关于来自两个不同数组的字符匹配,尽管它们不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55524274/

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