-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' 함수가 없습니다. –