【问题标题】:Skip white space and return one word at a time in C在 C 中跳过空格并一次返回一个单词
【发布时间】:2010-10-23 20:00:39
【问题描述】:

此代码应该跳过空格并一次返回一个单词。关于这段代码的几个问题: 当代码到达 *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

}

【问题讨论】:

    标签: c string pointers


    【解决方案1】:

    如果没有看到调用get_word 的代码,就不可能知道这个核心转储的原因。您命名的行的失败意味着您在第一个参数中传递了一些无效的东西。该行本身并没有什么问题,但如果word 没有指向足够大的可写内存来保存您的输出字符,那么您就有麻烦了。

    关于分配内存以保存它的问题的答案是肯定的 - 但是这可能是本地的(例如,调用者的局部变量中的 char 数组、全局或基于堆的(例如来自char * wordHolder = malloc(wordLimit);)。事实是你要求这支持您的参数 1 值是问题的猜测。

    【讨论】:

    • 您介意我从malloc 的返回值中删除演员表吗?
    • @R..,没有这个我得到一个编译错误,因为malloc返回void*:错误C2440:'initializing':无法从'void '转换为'char *'从 'void' 到指向非'void' 的指针的转换需要显式转换"
    • @Steve:那么你可能正在使用 C++ 编译器来编译 C 代码 :)
    • 是的,没错。有趣的是,malloc 的 MSDN CRT 文档说需要这种转换:“要返回指向 void 以外的类型的指针,请在返回值上使用类型转换。”
    • @Steve:您正在阅读 C++ 文档并使用 C++ 编译器,而不是 C 编译器。由于这是一项家庭作业,并且您将其标记为 C,因此我假设您应该编写 C。切换到 C 编译器。 C 和 C++ 不是同一种语言。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2016-12-10
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    相关资源
    最近更新 更多