需要知道如何在c中按空格解析单词.还需要知道我是否正确分配了内存? [英] Need to know how to parse words by space in c. Also need to know if I am allocating memory correctly?

查看:99
本文介绍了需要知道如何在c中按空格解析单词.还需要知道我是否正确分配了内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a program in c that reads in text from a text file then randomly selects words from the file and if the words are greater than or equal to six it appends the words together, removes the spaces, and finally prints the new word. (I am using the redirect on linux "<" to read in the file)

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)我是否为指针分配了正确的内存大小?

1) Am I allocating the correct memory size for the pointers?

2)如何不使用string.h库中的任何特殊方法(如strtok)按空格分析每个单词.然后如何将这些单词存储在指针* ptrWords中?

2) How can I parse each word by space without using any special methods from the string.h library (like strtok). Then how do I store those words in the pointer *ptrWords?

所以ptrWords应该看起来像这样:

so ptrWords should look like this:

奶酪|和|饼干

cheese | and | crackers

 0        1      2


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


Then I want to loop through ptrWords and check if the length of each word in the pointer is greater than or equal to six. If they are store them in the pointer ptrOutputWord.

所以ptrOutputWord应该看起来像这样:

so then ptrOutputWord should look like this:

奶酪|饼干

cheese | crackers

 0        1      


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


Finally, I want to print the values in ptrOutputWord as one word without spaces.

我试图解释我到底想做什么.感谢您能提前提供帮助的人.

I tried to explain what I want to do exactly. Thank you to anyone that can help in advance.

我更改了代码以仅反映应该读取字符的部分,并在每次读取新字符时将指针的大小重新分配一个,但未分配适当的内存量.

I changed the code to reflect only the piece that should read in the characters, and reallocate the size of the pointer by one each time a new character is read in, but the right amount of memory isn't being allocated.

推荐答案

您遇到了一些问题:

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

为什么要使用此标头?

#include <stdlib.h>

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

此变量需要有一个有用的起始值.

This variable needs to have a useful start value.

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

无需投射.

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

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

getchar返回并返回int,而不是char.

getchar returns and int, not a char.

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

我们需要比以前更多的字符,以及0的额外空间. 您应该在元素数量上加上+2(而不是+1):(strSize+2) * sizeof(<any type>)

We need one more character than before and extra space for the 0. You should add the +2 (not +1) to the number of elements: (strSize+2) * sizeof(<any type>)

通常,您不应该将realloc的结果直接分配给同一指针.万一失败,您将丢失旧的指针值.再说一次:不需要演员.

Normally you should not directly assign the result of realloc to the same pointer. In case it fails, you lose your old pointer value. Again: No cast needed.

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

如果失败,则无法继续!如上退出程序

If it fails, you cannot continue! Exit from the program just as above

    *ptrChFromFile = ch;

将字符放在扩大的缓冲区的开头.您应该在末尾添加.

You put the character to the start of the enlarged buffer. You should add at the end.

    strSize++;
  }

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

Now you have a bunch of characters in memory but no termination for the string.

  free(ptrChFromFile);
  return 0;
}

修复后,它看起来像这样:

After fixing it it looks like this:

#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中按空格解析单词.还需要知道我是否正确分配了内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆