gpt4 book ai didi

C++程序崩溃

转载 作者:太空狗 更新时间:2023-10-29 23:25:08 25 4
gpt4 key购买 nike

我有这个任务来实现 strcmp 函数。有时它运行正常,但有时它会崩溃。请帮助我。

#include <iostream>

using namespace std;

int mystrcmp(const char *s1, const char *s2);

int main()
{
cout<<mystrcmp("A","A")<<endl;
cout<<mystrcmp("B","A")<<endl;
cout<<mystrcmp("A","B")<<endl;
cout<<mystrcmp("AB","A")<<endl;

return 0;
}

int mystrcmp(const char *s1, const char *s2)
{
while (*s1==*s2)
{
s1++;
s2++;
}

if(*s1=='\0')
return(0);

return(*s1-*s2);
}

最佳答案

如果两个输入相同,它将崩溃,因为您的循环继续超出终止 nul 字符。

要解决此问题,您必须检查 nul 字符 inside 循环如下:

while (*s1==*s2) {

// if s1 points to nul character, then s2 should also, because of the ==
// which means we've reached the end of the strings and they are equal
// so return 0.
if(*s1=='\0')
return 0;

s1++;
s2++;
}

return *s1-*s2;

关于C++程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3965298/

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