0

I'm trying to implement a function that takes a string to parse and delimiter string as inputs, then returns a char array containing these parsed elements including empty chars if two delimiters are adjacent.

Below is my current code:

String* _split(String self, String delim) {
    char* selfCharArr = _get_value(self, NULL);
    char* delimCharArr = _get_value(delim, NULL);

    char** tokens = calloc((_length(self) + 2), sizeof(String));
    char* var;
    int index = 0;

    var = strsep(&selfCharArr, delimCharArr);
    while(var != NULL) {
        var = strsep(&selfCharArr, delimCharArr);
        tokens[index] = var;
        index++;
    }
    return (String*) tokens;
}

However, in testing I am finding that this will only return a NULL string, and I can't figure out why. No warnings or errors are produced and I've consulted the man pages.

9
  • Have you tried to step through the code in a debugger to see what happens? Commented Nov 15, 2019 at 10:56
  • I've not, could you recommend a good C debugger? I've just been using notepad++ to write it Commented Nov 15, 2019 at 10:58
  • How do you build your source? What environment and tools do you use for building and running? Commented Nov 15, 2019 at 11:05
  • I would add at least assert(index < _length(self) + 2); before tokens[index] as a first measure. Also, why is that you have char **tokens yet you allocate calloc(..., sizeof(String)) ? I think it would be better to just realloc the tokens pointer in the loop.
    – KamilCuk
    Commented Nov 15, 2019 at 11:11
  • I'm compiling and running on MINIX 3.2.1 Commented Nov 15, 2019 at 11:13

0

Your Answer

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

Browse other questions tagged or ask your own question.