开发者

C - Loop won't break

I want the loop to break when "Enter" is pressed. Any suggestions?

#include <stdio.h>
#include <st开发者_JS百科dlib.h>
#include <string.h>

#define len 20
#define limit 100

//Prototypes for functions
int read_word(char str[], int n);



int main(void)
{
  char *p;
  char word[len+1];
  int i=0, nwords = 0;

//Loop for reading in words and allocating an array 
  for (;;)
   {
      if (nwords == limit)
       {
          printf("Insufficient Space\n");
          break;
       }
      printf("Enter word: ");
      scanf("%c", &word);
      p = (char*) malloc(nwords*sizeof(char));
      p[i]= read_word(word, len);
      i++;

      if (p == NULL)
      {
          printf("Insufficient Space\n");
          break;
      }
  }

  for(i=0; i<nwords; i++)
      printf(" %s\n", p[i]);

  return 0;

  } 
int read_word(char str[], int n)
{
  char ch; 
  int i = 0;

  while((ch = getchar()) != '\n')
      if (i<n)
          str[i++] = ch; 
  str[i] = '\0';
  return i;
}


Your scanf call reads the first character, and then your read_word function overwrites it. If the scanf call reads the newline, it will then be ignored.

The lines:

  p = (char*) malloc(nwords*sizeof(char));
  p[i]= read_word(word, len);

... also appears wrong. read_word returns an integer (the length of the string read), but you are storing into a char array. Also, you are re-allocating the memory for p each time through the loop, so the values stored previously will be lost.

To fix:

  • change p to be an int *, and initialize it to null
  • change the malloc call to a suitable realloc
  • remove the call to scanf entirely
  • move the check for p == null before the assignment of `p = (char*) malloc(nwords*sizeof(char));'

Or: is p meant to actually be an array of strings (the words themselves) rather than the word length? In that case you have to:

  • change p to be an char **
  • change the allocation size (for the realloc call) to nwords * sizeof(*p)
  • allocate (using malloc) storage for each word instead of having word be a stack-allocated array
  • set p[i] = word; rather than the current assignment.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜