strtok中的分段错误
我一直在收到这个错误。 我很确定它与内存分配有关,但我不太确定如何修复它。
#include #include #include #include char * VOWELS ="aeiouAEIOU"; void printLatinWord(char *a); int main(int argc, char **argv){ char phrase[100]; char *word = malloc(sizeof(char) *100); printf("Enter the phrase to be translated: \n"); fgets(word, 100, stdin); printf("The phrase in Pig Latin is:\n"); word = strtok(phrase, " "); printLatinWord(word); return 0; } void printLatinWord(char *word){ while (strchr(VOWELS, *word) == NULL){ char consonant = *word; char *to=word, *from=word+1; while (*from) *to++=*from++; *to=consonant; } printf("%say\n", word); }
输出给出“分段故障(核心转储)”
fgets(word, 100, stdin); word = strtok(phrase, " ");
你在这里有错误的参数。 您正在将未初始化的phrase
中的字符串拆分,然后将结果分配给word
从而覆盖指向先前分配的内存的指针。
您可能希望fgets
将输入读入phrase
而不是word
。