Search code examples
cmallocclangreallocstrtok

Splitting a string with strtok() goes wrong


I'm trying to get input from the user while allocating it dynamically and then "split" it using strtok.

Main Questions:

  1. Im getting an infinite loop of "a{\300_\377" and ",".
  2. Why do i get a warning of "Implicitly declaring library function "malloc"/"realoc" with type void"

Other less important questions:

3.i want to break, if the input includes "-1", how do i check it? As you can see it breaks now if its 1.

4.In the getsWordsArray() i want to return a pointer to an array of strings. Since i dont know how many strings there are do i also need to dynamically allocate it like in the getInput(). (I dont know how many chars are there in each string)

   int main(int argc, const char * argv[])
    {
        char input = getInput();
         getWordsArray(&input);  
    }
    char getInput()
    {   
        char *data,*temp;
        data=malloc(sizeof(char));
        char c; /* c is the current character */
        int i; /* i is the counter */
        printf ("\n Enter chars and to finish push new line:\n");
        for (i=0;;i++) {
            c=getchar(); /* put input character into c */
            if (c== '1')                // need to find a way to change it to -1
                break;
            data[i]=c; /* put the character into the data array */
            temp=realloc(data,(i+1)*sizeof(char)); /* give the pointer some memory */
            if ( temp != NULL ) {
                data=temp;
            } else {
                free(data);
                printf("Error allocating memory!\n");
                return 0 ;
            }
        }   
        printf("list is: %s\n",data); // for checking
        return *data;     
    }

    void getWordsArray(char *input)
    {
        char *token;
        char *search = " ,";
        token = strtok (input,search);
        while (token != NULL ) {
            printf("%s\n",token);
            token = strtok(NULL,search);
        }
    }

EDIT: i noticed i forgot to "strtok" command so i changed it to token = strtok(NULL,search);

I still get wierd output on the printf:

\327{\300_\377

Solution

  • Change:

    int main(int argc, const char * argv[])
    {
        char input = getInput();
        getWordsArray(&input);  
    }
    

    to:

    int main(int argc, const char * argv[])
    {
        char *input = getInput();
        getWordsArray(input);  
    }
    

    with a similar to the return value of getInput():

    char *getInput()
    {   
        // ...
        return data;
    }
    

    In your code, you were only saving the first character of the input string, and then passing mostly garbage to getWordsArray().

    For your malloc() question, man malloc starts with:

    SYNOPSIS
       #include <stdlib.h>
    

    For your getchar() question, perhaps see I'm trying to understand getchar() != EOF, etc.