Question

getWordsArray() gets a pointer to a char array - the input.

Im trying to split that input and store each word in a char array. And eventually return that char array.

   char *getWordsArray(char *input)
    {
        char *token;
        char *search = " ,";
        char *splited, *temp;
        int counter=0;
        splited = malloc(sizeof(char)*15);
        token = strtok (input,search);
        while (token != NULL ) {
            printf("%s\n",token);
            token = strtok (NULL,search);
          //  splited[counter] = *token;  //aliasing ?
            strcpy(&splited[counter] , token);
            temp= realloc(splited,(counter+1)*sizeof(token));
            if (temp !=NULL) {
                splited = temp;
            } else{
                free(splited);
                printf("Error allocating memory!\n");
                return 0 ;
            }
            counter++;
        }
        printf("list is: %s\n",splited);
        return splited;
    }

It seems like it works since it prints correctly. But i get:

EXC_BAD_ACCESS

on

strcpy(&splited[counter] , token);

Anyone can point me out whats wrong ?

Was it helpful?

Solution

Your function return type is all wrong; it needs to be char **, not just char *. The allocation strategy in the function is wrong, too, therefore. You need to allocate an array of char * as well as an array of char for each component word that is stored in the array of char *.

OTHER TIPS

When you copy the string, e.g. on strcpy(&splited[counter] , token);, it is very likely, that it's too long for the destination. That is because you do not allocate an array of strings but an array of char.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top