![](/img/trans.png)
[英]C - Using strtok to split an array of strings into an array of characters
[英]a function split strings without using strtok and return a new array
我正在嘗試編寫一個拆分字符串的函數,並且不允許使用 strtok。
假設字符串只有單詞之間有空格,並且每對單詞之間只有一個空格。
我在堆上分配數組的每個單詞和單詞。 但是,運行程序的結果是: Segmentation fault(core dumped) 。 任何幫助表示贊賞。
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
void displayWords(char *wordArray[], int numWords){
if (wordArray != NULL){
int i;
for (i=0; i<numWords;i++)
printf("%i. \"%s\"\n", i+1, wordArray[i]);
}
}
int countSpaces(char theString[]) {
int spaces = 0, len = strlen(theString);
for(int i=0;i < len;i++) {
if(theString[i] == ' ') {
spaces++;
}
}
return spaces;
}
char** splitString(char theString[], int *arraySize){
int i,x,y=0;
int start,end=0; //index;
char *word; //create an array with char as elements
char **words;//create an array with words as its elements
int stringLen=strlen(theString);
int numOfWords = countSpaces(theString)+1;
*arraySize = numOfWords;
word = (char*)malloc(stringLen+1);
words = (char**)malloc(numOfWords);
for(x=0;x<=stringLen;x++){
if (theString[x]==' ' || theString[x]=='\0'){
for(x=start;x<=end;x++){
word[y]=theString[x];
y++;
strcpy(words[i],word);//copy the substring into words
words[i] = (char*)malloc(strlen(word)+1);
i++;
free(word);
start=end+2; //next start is the element right after the space
end=end+2; //do the same thing on end index
}
}
else{ //when theString[x] != ' '
end++;
}
}
words[*arraySize]=='\0';
return words;
}
int main(){
int size;
char test[]="it is a cat";
char **words = splitString(test, &size);
displayWords(words, size);
return 0;
}
單詞 = (char**)malloc(numOfWords);
這應該是:
words = malloc(numOfWords*sizeof(char*));
如果未指定sizeof(char*)
,則可能不會分配所需的內存量。 因此,您最終可能會訪問未分配的位置。 這會給您帶來分段錯誤。 無需malloc
的輸出
for(x=0;x<=stringLen;x++)
這應該是:
for(x=0;x<stringLen;x++)
for(x=開始;x<=結束;x++)
start
尚未初始化。 ( int start,end=0; )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.