该代码应该跳过空格并一次返回一个单词.关于这段代码的几个问题:当代码到达*word ++ = c时; 我得到一个核心转储.我是否正确写过这一行?并返回正确.我需要以某种方式分配内存来存储这个词吗?
//get_word
int get_word(char *word,int lim){
int i=0;
int c;
int quotes=0;
int inword = 1;
while(
inword &&
(i < (lim-1)) &&
((c=getchar()) != EOF)
){
if(c==('\"')){//this is so i can get a "string"
if (quotes) {
inword = 0;
}
quotes = ! quotes;
}
else if(quotes){ //if in a string keep storing til the end of the string
*word++=c;//pointer word gets c and increments the pointer
i++;
}
else if(!isspace(c)) {//if not in string store
*word++=c;
i++;
}
else {
// Only end if we have read some character ...
if (i)
inword = 0;
}
}
*word='\0'; //null at the end to signify
return i; //value
Run Code Online (Sandbox Code Playgroud)
}
如果不看到调用 的代码,就不可能判断为什么这个核心转储get_word。您命名的行的失败意味着您在第一个参数中向其传递了无效的内容。该行本身没有任何问题,但如果它word没有指向足够大的可写内存来容纳输出字符,那么您就有麻烦了。
关于分配内存来保存它的问题的答案是肯定的 - 但是这可能是本地的(例如调用者本地变量中的 char 数组、全局的或基于堆的(例如来自char * wordHolder = malloc(wordLimit);)。您所问的事实支持了猜测你的参数 1 值是问题所在。