-5
私はユーザが入力した文字列を取り、それを動的に割り当てられた2次元配列を使って個々の単語に分割する関数を持っています。単語は区切り記号で区切られ、区切り記号は区切り記号で区切られています。ここで私はこのプログラムを実行するたびにsegfaultを取得し続けますが、なぜわかりません
が私のコードです:
int countWords(const char * sentence, char * delims)
{
int wordsInArray = 0;
int count = 0;
while(*(sentence + count) != '\0')
{
if(*(sentence + count) == *delims && *(sentence + count + 1) != *delims)
{
wordsInArray++;
}
if(*(sentence + count + 1) == '\0')
{
wordsInArray++;
}
count++;
}
return wordsInArray;
}
int getLength(const char * sentence)
{
const char *p = sentence;
while(*p != '\0')
{
p++;
}
return p-sentence;
}
char ** getWords(const char * sentence, int & wordcount)
{
char delims[] = " .,\t?!";
int sentenceLength = getLength(sentence);
wordcount = countWords(sentence, delims);
char ** words;
words = new char *[wordcount];
int length = 0;
int count = 0;
for (int a = 0; a < sentenceLength; a++)
{
if(*(sentence + a) != *delims)
{
length++;
}
else if ((*(sentence + a) == *delims && *(sentence + a + 1) != *delims) || *(sentence + a) == '\0')
{
*(words + count) = new char[length+1];
for (int z = 0; z < length; z++)
{
*(*(words + count) + z) = *(sentence + z);
}
length = 0;
count++;
}
}
return words;
}
しかし、私のcountWords
機能が正しく文字列内の単語を数えていない、と私は理由を知りません。
問題点はわかりませんが、 '*(sentence + a)'などの式を同等の 'sentence [a]'として書くのは慣用です。そのイディオムを使用すると、あなたのプログラムはおそらくより読みやすくなります。 –
'getLength()'は 'strlen()'の独自の実装のようです。あなたの仕事で 'strlen()'を使うことは許されていませんか?第二に、あなたは 'delims'文字列を持っていますが、あなたはその中で最初の文字だけを使用します。 –
このプログラムは実行できません。 'main'関数はありません。 –