c - 需要知道如何在 c 中按空格解析单词。还需要知道我是否正确分配内存?

标签 c pointers malloc tokenize dynamic-arrays

我正在用 c 编写一个程序,该程序从文本文件中读取文本,然后从文件中随机选择单词,如果单词大于或等于 6,它会将这些单词附加在一起,删除空格,最后打印新词。 (我在 linux 上使用重定向“<”来读取文件)

Example input: "cheese and crackers"

New word should be: cheesecrackers

代码如下:

int main (void)
{
    int ch;
    char *ptrChFromFile;
    int strSize = 1;
    int i;
    int numberOfWords = 1;

    ptrChFromFile = malloc (sizeof (char));

    if (ptrChFromFile == NULL) {
        puts ("COULDN'T ALLOICATE MEMORY");
        exit (EXIT_FAILURE);
    }

    while ((ch = getchar ()) != EOF) {
        ptrChFromFile =
            realloc (ptrChFromFile, (strSize + 1) * sizeof (char));

        if (ptrChFromFile == NULL) {
            puts ("failed to allocate memory");
            exit (EXIT_FAILURE);
        }

        if (ch == ' ') {
            numberOfWords++;
        }

        ptrChFromFile[strSize] = ch;
        strSize++;
    }

    ptrChFromFile[strSize] = 0;

    char **ptrWords = malloc (sizeof (char *) * strSize);


    for (i = 0; i < strSize; i++) {
        if (ptrChFromFile[i] != ' ') {
            ptrWords[i] = &ptrChFromFile[i];
        }
        else {
            ptrWords[i] = 0;
        }
    }

    free (ptrChFromFile);
    free (ptrWords);
    return 0;
}

我正在努力解决的问题是:

1) 我是否为指针分配了正确的内存大小?

2) 如何在不使用 string.h 库(如 strtok)的任何特殊方法的情况下按空格解析每个单词。那么如何将这些单词存储在指针 *ptrWords 中?

所以 ptrWords 应该是这样的:


cheese | and | crackers

 0        1      2

然后我想遍历 ptrWords 并检查指针中每个单词的长度是否大于或等于 6。如果它们存储在指针 ptrOutputWord 中。

那么 ptrOutputWord 应该是这样的:


cheese | crackers

 0        1      

最后,我想将 ptrOutputWord 中的值打印为一个不带空格的单词。

我试图准确地解释我想做什么。感谢任何可以提前提供帮助的人。

编辑:我更改了代码以仅反射(reflect)应读入字符的部分,并在每次读入新字符时将指针的大小重新分配一个,但未分配正确数量的内存.

最佳答案

你有几个问题:

#include <stdio.h>
#include <time.h>

为什么是这个标题?

#include <stdlib.h>

int main()
{
  char ch, *ptrChFromFile; 
  int strSize;

这个变量需要有一个有用的起始值。

  ptrWordsFromFile = (char*)malloc(sizeof(char));

无需转换。

  if(ptrChFromFile == NULL)
  {
     puts("COULDN'T ALLOICATE MEMORY");
     exit(EXIT_FAILURE);
  }

  while((ch = getchar()) != EOF)

getchar返回和int , 不是 char .

  {
    ptrChFromFile  = (char*)realloc(ptrChFromFile, strSize * sizeof(char)+1);

我们需要比以前多一个字符,并为 0 添加额外的空间. 您应该将 +2(而不是 +1)添加到元素数量:(strSize+2) * sizeof(<any type>)

通常你不应该直接分配 realloc 的结果到同一个指针。万一失败,您将丢失旧的指针值。再次声明:不需要强制转换。

    if(ptrChFromFile == NULL)
      {puts("failed to alloicate memory");}

如果失败,您将无法继续!和上面一样退出程序

    *ptrChFromFile = ch;

您将字符放在放大缓冲区的开头。你应该在最后添加。

    strSize++;
  }

现在内存中有一堆字符,但字符串没有终止符。

  free(ptrChFromFile);
  return 0;
}

修复后它看起来像这样:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int ch;
  char *ptrChFromFile; 
  int strSize = 0;

  ptrWordsFromFile = malloc(sizeof(char));

  if (ptrChFromFile == NULL)
  {
     puts("COULDN'T ALLOICATE MEMORY");
     exit(EXIT_FAILURE);
  }

  while ((ch = getchar()) != EOF)
  {
    ptrChFromFile = realloc(ptrChFromFile, (strSize+2) * sizeof(char));

    if (ptrChFromFile == NULL)
    {
      puts("failed to allocate memory");
      exit(EXIT_FAILURE);
    }

    ptrChFromFile[strSize] = ch;
    strSize++;
  }
  ptrChFromFile[strSize] = 0;

  // Now add detection and storing of separate words
  // (You might omit storing words that are too short)
  // Select random words and add together.

  free(ptrChFromFile);
  return 0;
}

关于c - 需要知道如何在 c 中按空格解析单词。还需要知道我是否正确分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55035450/

相关文章:

c - 如何在STM32F3上实现没有CubeMX的PWM?

c - 在 C 中将 2 维数组作为函数参数传递时出错

c - malloc 实际分配了多少内存,并且可以将变量存储在分配有 malloc 的数组中以节省内存?

c - malloc() 内存损坏

c - 使用 'if' 查找最大值和最小值

无法释放结构体的数据

c++ - 将指针转换为 (const) 引用

c - 将数组指向相同的内存位置

pointers - 如何在 Go 中使用接收器?

c - Kernighan和Ritchie malloc自由逻辑