简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM