-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'功能。 –