私のコードはセグメンテーションフォールトを持っていますか?文字列に2つの同じ文字があるかどうかを調べようとしています。しかし、それはどのようにセグメンテーションフォルトを持っていますか?セグメンテーションフォールトC++なぜ私のプログラムは私にセグメンテーションフォールトを与えていますか
#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;
}
それがために 'する必要があります(int型J = 1; jの<長さ; J ++)'ここ – Tyger
は、代替です:256 'bool'sの配列を作成します。配列をfalseに初期化します。 'word'の各文字を' unsigned char'として一つずつ探し、文字のインデックスの 'bool'が真でない場合は真にします。 boolがtrueの場合、重複してtrueを返すことができます。 trueを返さずに 'word'の終わりにすると、falseを返します。 – user4581301
std :: stringを使用します。 –