-2

I am basically trying to get user input as a string, and cut it into several different ones where each one of them is stored in a position in the array, I want to cut the strings when the user inputs a comma (,). For example, let's assume we declare an array of chars word[4] with 4 spaces in it, and the user inputs "strawberry,banana,apple,orange" I want my code to store it in the array such that word[0] = strawberry word[1] = banana word[2] = apple word[3] = orange. I am new to c and i read a post about fgets and it sounded very useful. I attached the code i had if you are interested, I had segmentaion fault (core dumped) error though. I am mainly looking for ideas to try and implement what i mentioned earlier, not necessarily a fix for the code. Thanks!

PS Most of the code i attached is NOT MINE it belongs to RoadRunner. I got most of the fgets code from them as that is where I came to know it from and it included error checking. link for their answer: https://stackoverflow.com/a/41518512/14964842

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

#define NUMSTR 1
#define BUFFSIZE 100
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))

int main(void) {
    char *words[NUMSTR];
    char buffer[BUFFSIZE];
    size_t i, j, lastStr = 0, count = 0, slen; /* can replace size_t with int if you prefer */

    /* loops only for three input strings */
    for (i = 0; i < NUMSTR; i++) {

        /* read input of one string, with error checking */
        printf("Enter a word: ");
        if (fgets(buffer, BUFFSIZE, stdin) == NULL) {
            fprintf(stderr, "Error reading string into buffer.\n");
            exit(EXIT_FAILURE);
        }

        /* removing newline from buffer, along with checking for overflow from buffer */
        slen = strlen(buffer);
        if (slen > 0) {
            if (buffer[slen - 1] == '\n') {
                buffer[slen - 1] = '\0';
            } else {
                printf("Exceeded buffer length of %d.\n", BUFFSIZE);
                exit(EXIT_FAILURE);
            }
        }

        /* checking if nothing was entered */
        if (!*buffer) {
            printf("No string entered.\n");
            exit(EXIT_FAILURE);
        }

        /* allocate space for `words[i]` and null terminator */
        words[count] = malloc(strlen(buffer) + 1);

        /* checking return of malloc, very good to do this */
        if (!words[count]) {
            printf("Cannot allocate memory for string.\n");
            exit(EXIT_FAILURE);
        }
        /**
         * Starting from here is my code.
         * I am trying to check every character in the string till i find the comma.
         * If it is found, then the program should store everything that is before that comma and the one before if it
         * exists.
         */
        for (i = 0; i < NELEMS(buffer)-1; i++)
        {
            if(buffer[i] = ",")
            {
                char tempStorage[i];
                tempStorage[i] = malloc(strlen(buffer) + 1);
                for(j = i-1; j >= lastStr; j--)
                {

                    buffer[j] = tempStorage[j];
                    tempStorage[i] = '\0';
                    /* if everything is fine, copy over into your array of pointers */
                    strcat(words[count], tempStorage);
                }
                free(tempStorage[i]);
                tempStorage[i] = NULL;
            }
        }
    }

    /* reading input is finished, now time to print and free the strings */
    printf("\nYour strings:\n");
    for (i = 0; i < count; i++) {
        printf("words[%zu] = %s\n", i, words[i]);
        free(words[i]);
        words[i] = NULL;
    }

    return 0;
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Icen
  • 123
  • 8
  • This is the kind of job which you can use [`strtok()`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strtok-strtok-l-wcstok-wcstok-l-mbstok-mbstok-l?view=msvc-170) for. – Weather Vane Dec 27 '21 at 13:27
  • I think array of chars word[4] cannot hold "word[0] = strawberry word[1] = banana word[2] = apple word[3] = orange" but it can only hold "stra" where word[0] ='s' ... word[3]='a' – Mahesh Jamdade Dec 27 '21 at 13:27
  • @WeatherVane Thank you! That's exactly what i needed. Couldn't find it anywhere. – Icen Dec 27 '21 at 13:33
  • @MaheshJamdade Can it not? I thought i can contain strings in an array of characters. I will have to research an array of strings. Thanks! – Icen Dec 27 '21 at 13:33
  • `if(buffer[i] = ",")` is very wrong. Did you mean `if(buffer[i] == ',')`? – Weather Vane Dec 27 '21 at 13:37
  • @WeatherVane Yes i did! Sorry, i need to fix that in the code. Such a dumb mistake. – Icen Dec 27 '21 at 13:43
  • `tempStorage[i] = malloc(strlen(buffer) + 1);` is wrong, did you mean the array `char tempStorage[i];` to be `char *tempStorage[i];`? Please take notice of the compiler warnings. – Weather Vane Dec 27 '21 at 13:43
  • Please don't make live updates to the code posted, reflecting the progress. Rolled back. Anyway, you didn't make the correction I suggested. There are *two* faults, a) using `=` instead of `==` and b) giving a pointer to the string `","` instead of the character `','`. – Weather Vane Dec 27 '21 at 13:44
  • @WeatherVane Thank you for all the help! I have been fixing the faults in my code and It is partially working. I am also looking into strtok() which looks very promising. Thanks again! – Icen Dec 27 '21 at 13:52
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Jan 04 '22 at 17:17

1 Answers1

0

There are several problems in your program: count will be always 0 you are not increasing it.

There is no need for NELEMS because you are already counting chars.

The line:

   buffer[j] = tempStorage[j];
   //should be:
   tempStorage[j] = buffer[j]

Here you are not freeing memory, i don't know what are you trying to do here.

    free(tempStorage[i]);
    tempStorage[i] = NULL

These lines should be outside the inner loop, you are copying the entire word each time you assign a letter which is meaningless:

    tempStorage[i] = '\0';
    /* if everything is fine, copy over into your array of pointers */
    strcat(words[count], tempStorage);

You already freed the memory so why assigning NULL to a freed memory it will give you segmentation fault:

     free(words[i]);
     words[i] = NULL;

Try to allocate space in word after calculating the length of the word you are trying to copy, you are allocating a space for each word that is equal to the entire line which is a waste of memory (although not critical but it's a bad practice)

Read about strchr it will be helpful and will save you the loops.

Bashi
  • 174
  • 6