在C语言中跳过空格并逐个返回单词

5

这段代码的作用是跳过空格并逐个返回单词。对于这段代码,有几个问题:当代码到达*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

}

1个回答

2

如果没有看到调用get_word的代码,就无法确定为什么会出现核心转储。你所指定的行失败意味着在第一个参数中传递了一些无效的内容。这行本身没有问题,但是如果word没有指向足够大的可写内存以容纳输出字符,那么就会出现问题。

关于分配内存以容纳它的问题,答案是肯定的 - 但是这可以是局部的(例如,调用者的局部变量中的char数组),全局的,或基于堆(例如,从char * wordHolder = malloc(wordLimit);)。您提出这个问题表明你的第一个参数的值可能有问题。


你介意我从malloc的返回值中删除强制转换吗? - R.. GitHub STOP HELPING ICE
@R..,没有这个的话我会得到编译错误,因为malloc返回的是void*:错误C2440:“初始化”:无法从“void”转换为“char” 从'void*'到非'void'指针的转换需要显式转换。 - Steve Townsend
@Steve:那么你可能正在使用C++编译器来编译C代码 :) - fredoverflow
是的,没错。有趣的是,malloc 的 MSDN CRT 文档说需要进行类型转换:"要返回指向除 void 以外的其他类型的指针,请在返回值上使用类型转换。" - Steve Townsend
@Steve:你正在阅读C++文档并使用C++编译器,而不是C编译器。由于这是一项作业任务,并且你标记为C,我会假设你应该写C语言。请切换到C编译器。C和C++根本不是同一种语言。 - R.. GitHub STOP HELPING ICE
@R.. - 我不确定这一点,所以查阅了我的标准参考资料(因为我是MS中心),发现CRT的内容是错误的,或者最多只能说明在C++编译CRT使用时适用。无论如何,我会进行建议的编辑 - 谢谢。 - Steve Townsend

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接