I have a function that needs to parse a line into an array of strings. For example, if given the line
test1 test2 test3
it should return the array ["test1","test2","test3"]. I also know that all lines are maximum 81 characters. This is my current code
void parseLine(char *line, char **words){
words = malloc(81*sizeof(char*));
char *p = line;
char *currentWord = (char *)calloc(strlen(line)+1,sizeof(char));
int wordIndex = 0;
while (*p != '\0'){
while (isspace(*p++));
p--;
while (!isspace(*p) && *p != '\0'){
strncat(currentWord,p++,1);
}
words[wordIndex++] = currentWord;
currentWord = calloc(strlen(line)+1,sizeof(char));
}
words[wordIndex] = NULL;
}
My idea with this is that because I can't return a non-static array created within the function, I will use a pre-existing array. However, this doesn't work, and I think it is because the pointers to the strings are also invalidated when the function ends. I've seen some examples which make it work, such as this, by using the "" string declaration, but such a method doesn't work for me. What can I do?
currentWord = calloc(0,sizeof(char));is an array of0elements. It cannot be used. You should use a size, like you did forwordsstrlen(line)==>strlen(line) + 1for the 0-terminator.