gpt4 book ai didi

c++ - 段错误c++为什么我的程序给我段错误

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

为什么我的代码有段错误?我想看看字符串中是否有两个相同的字母。但是怎么会出现段错误呢?

#include<iostream>
#include<cstring>
using namespace std;

bool match(char[], int);

int main()
{
char word[20];
cout << "Enter a word: ";
cin >> word;
int length = strlen(word);
if (match(word, length)) cout << "It has two letters that are the same" <<
endl;
else cout << "There is no same letters" << endl;
return 0;
}

bool match(char word[], int length)
{
bool found = false;
for (int i = 0; i < length; i++)
{
for (int j = 1; i < length; j++)
{
if (j <= i || j == length || i == length) continue;
if (word[i] == word[j]) found = true;
}
}
return found;
}

最佳答案

您是有意将 i 包含在您的 j 循环中还是偶然?

引用:

 "for (int j = 1; i < length; j++)"

Should this be: for (int j; j<length; j++)?

请记住,一些段错误具有内存管理问题,而不仅仅是逻辑问题。检查以确保您的 sizeof 运算符正常运行,这就是我通常搞砸的地方

关于c++ - 段错误c++为什么我的程序给我段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45156449/

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