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 ?
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 *
.