[C]:使用strcpy()分割为字符串数组的分段错误

时间:2018-10-15 04:48:43

标签: c segmentation-fault strtok strcpy strcat

我的任务是编写一个函数,该函数接收用户的输入字符串,将其标记为几个字符串,每个字符串包含输入句子中的单个单词,然后反转该句子。结果将是句子输入,但单词顺序相反。

就目前而言,我只是具有以下功能:接受输入,将其标记为单个单词,将这些单词存储到数组中,然后按顺序打印每个单词。我还没有逆转所写单词顺序的过程。

这是到目前为止我已经处理过的函数的代码:

void reverse(void){
printf("\n\n%s\n", "Reverse words in String: ");

char input[200];
printf("\n%s", "Enter string\n> ");
scanf("%s", &input);

char reverseSentence[200];
char sentenceParts[20][200];
int wordCount = 0;

char *thisWord = strtok(input, " ");
strcpy(sentenceParts[wordCount], thisWord);
wordCount++;


while(thisWord != NULL){
    thisWord  = strtok(NULL, " ");
    strcpy(sentenceParts[wordCount], thisWord);
    wordCount++;
}

printf("\n\n");

for(int i = 0; i < wordCount + 1; ++i){
    printf("%s%s", sentenceParts[i], " ");
}
}

问题出在while语句中:

while(thisWord != NULL){
    thisWord  = strtok(NULL, " ");
    strcpy(sentenceParts[wordCount], thisWord);
    wordCount++;
}

该程序退出,并在strcpy语句中出现段错误。我一生无法理解为什么要这么做。似乎在while循环之外一切正常。

有什么想法吗?我已经在这个问题上停留了很多时间,并且找不到太多其他资源可以提供帮助。

1 个答案:

答案 0 :(得分:1)

使用下一个标记更新thisWord应该在循环主体的末尾进行。照原样,您最终将使用NULL更新thisWord,然后使用NULL调用strcpy。那就是你的段错误。

因此循环应如下所示:

char *thisWord = strtok(input, " ");
while(thisWord != NULL){
    strcpy(sentenceParts[wordCount], thisWord);
    wordCount++;
    thisWord  = strtok(NULL, " ");
}

另一个问题(在注释中由@WhozCraig指出)是您使用scanf("%s", ...)输入行。这是行不通的,因为scanf将停在第一个空格字符处。因此,您一次只能从scanf得到一个单词。要获得整行,请使用fgets函数。