I'm trying to make a function that splits a cstring into an array of words. Eg. if I send in "Hello world" then I'd get an array with two places where the 1st place has the element "Hello", second "world". I'm getting segmentation fault and I can't for the life of me figure out what seems to be wrong.
In the for-loop I am checking how many spaces there are, which determines how many words there are in total (spacing is always N-1, N = number of words). Then I tell the program to add 1 to the counter (Because of N-1).
I declare a char* array[] in order to keep each of the individual words seperated, not sure if I need counter+1 here (because of the \0?)
This is where the tricky part comes in. I use strtok to seperate each words (using " "). I then malloc each position of char*array[] so that it has enough memory to store the words. This is done until there are no more words to put in.
I would really appreciate it if someone could give me a hint of which part is causing the segmentation fault!
void split(char* s){
int counter = 0;
int pos = 0;
for(int i=0; s[i]!='\0'; i++){
if(s[i] == ' '){
counter ++;
}
}
counter += 1;
char* array[counter+1];
char *token = strtok(s, " ");
while(token != NULL){
array[pos] = malloc(strlen(token));
strcpy(array[pos], token);
token = strtok(NULL, " ");
pos++;
}
malloc(strlen(token))-->malloc(strlen(token)+1)