C - 循环不会中断

标签 c string loops

我希望在按下“Enter”时中断循环。有什么建议吗?

#include <stdio.h>
#include <stdlib.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;
}

最佳答案

您的 scanf 调用读取第一个字符,然后您的 read_word 函数会覆盖它。如果 scanf 调用读取换行符,它将被忽略。

行:

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

...也显得错误。 read_word 返回一个整数(读取的字符串的长度),但您将存储到 char 数组中。此外,每次循环都会为 p 重新分配内存,因此之前存储的值将会丢失。

修复:

  • p 更改为 int *,并将其初始化为 null
  • malloc 调用更改为合适的 realloc
  • 完全删除对 scanf 的调用
  • p == null 的检查移至“p = (char*) malloc(nwords*sizeof(char));”的赋值之前

或者:p实际上是一个字符串数组(单词本身)而不是单词长度吗?在这种情况下,您必须:

  • p 更改为 char **
  • 将分配大小(用于 realloc 调用)更改为 nwords * sizeof(*p)
  • 为每个单词分配(使用malloc)存储空间,而不是让word成为堆栈分配的数组
  • 设置p[i] = word;而不是当前的赋值。

关于C - 循环不会中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5920381/

相关文章:

python - 使用 ctypes 从 C++ 函数返回字符串给出大的 int,而不是 char 指针

php - 如何显示 PHP 字符串 "AS IS"(里面的特殊字符)?

c - 如何为只读字符串重新分配内存?

javascript - 动态分层 Javascript 对象循环

c - C中的过滤字符串

使用 Curses 在 C 程序中创建一个盒子

c - 代码错误,用C语言编程

python - 如何修复 __str__ 方法产生的无限循环?

python - 我如何完成以下检查 list 中的第 2 项和/或完成该计划?

c - makefile : it doesn't behave the way I've been taught it should and I'm not sure what to do 出现问题