2

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?

12
  • 3
    currentWord = calloc(0,sizeof(char)); is an array of 0 elements. It cannot be used. You should use a size, like you did for words Commented Jul 7, 2022 at 11:57
  • I am aware, but that part works just as intended even with the weird array declaration. If I look at the array before I leave the function, everything is parsed correctly, the problems start when I leave the function. Nevertheless I will change that Commented Jul 7, 2022 at 11:58
  • 1
    "that part works". No it doesn't. It is wrong and needs to be fixed. You are writing to invalid memory and that results in Undefined Behaviour. And changing it from 0 to 1 doesn't help much. It needs to be big enough to fit the entire string. Commented Jul 7, 2022 at 12:02
  • 1
    strlen(line) ==> strlen(line) + 1 for the 0-terminator. Commented Jul 7, 2022 at 12:11
  • 1
    The return value somehow fixed it, I don't fully understand, but it works now. Thanks! Commented Jul 7, 2022 at 12:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.