我一直收到这个错误。我很确定这与内存分配有关,但我不太确定如何修复它。
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
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);
}输出结果是“分段故障(核心转储)”。
发布于 2011-11-12 00:39:01
fgets(word, 100, stdin);
word = strtok(phrase, " ");你这里的参数是错误的。在未初始化的phrase中拆分字符串,然后将结果赋值给word,从而覆盖指向先前分配的内存的指针。
您可能打算让fgets将输入读入phrase,而不是word。
https://stackoverflow.com/questions/8097074
复制相似问题