-5
我有一個函數,它接受用戶輸入的字符串,並使用動態分配的二維數組將其拆分爲單個單詞。單詞由分隔符分隔,用作指示一個單詞結束和另一個單詞開始的位置。我每次運行此程序時都會收到段錯誤,但我不明白爲什麼
這裏是我的代碼:
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)'這樣的表達式寫成等價的'句子[a]'是一種習慣用法。如果你使用這個習慣用法,你的程序可能會更具可讀性。 –
而'getLength()'似乎只是你自己實現'strlen()'。你不允許在你的工作中使用'strlen()'嗎?其次,你有一個'delims'字符串,但你只能使用它的第一個字符。 –
這個程序不能運行 - 沒有'main'功能。 –