开发者

Skip white space and return one word at a time in C

This code is supposed to skip white space and return one word at a time. A couple of questions on this code: When the code gets to the *word++=c; line I get a core dump. Have I written this line correctly? and is return correct. And Do I need to somehow allocate memory to store the word?

//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

}


It's impossible to tell why this core dumps without seeing the code that calls get_word. The failure at the line you named implies that you are passing it something invalid in the first parameter. There's nothing wrong with that line in and of itself, but if word does not point to writable memory large enough to hold your output characters, you are in trouble.

The answer to your question about allocating memory to hold it is yes - however this could be local (e.g. a char array in the caller's local variables, global, or heap-based (e.g. from char * wordHolder = malloc(wordLimit);). The fact you are asking this supports the guess that your parameter 1 value is the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜