Need to know how to parse words by space in c. Also need to know if I am allocating memory correctly?

三世轮回 提交于 2019-12-02 09:03:17

问题


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

Here is the code:

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;
}

The things that I am struggling with are:

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

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?

so ptrWords should look like this:


cheese | and | crackers

 0        1      2

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.

so then ptrOutputWord should look like this:


cheese | crackers

 0        1      

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.

EDIT: 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.


回答1:


You have a few issues:

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

Why this header?

#include <stdlib.h>

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

This variable needs to have a useful start value.

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

No need to cast.

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

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

getchar returns and int, not a char.

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

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

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;
}


来源:https://stackoverflow.com/questions/55035450/need-to-know-how-to-parse-words-by-space-in-c-also-need-to-know-if-i-am-allocat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!