Search code examples
c++freestanding

Split char* at delimiter in freestanding mode c++


I am trying to write my own operating system. I have followed the tutorials on the OSDev Wiki, and I am now working on writing a console mode, with commands. I need to be able to split a char* into a char**, without all the library functionality (hence freestanding). I have tried iterating through until I meet my delimiter etc, but however I do it, I just get garbage stuck on the end of my first result. What am I doing wrong? This is what I have so far:

static char** splitStr (char* string, char delim) {

    char returner[VGA_WIDTH][255];
    int loc = 0;
    int innerLoc = 0;
    for (int i = 0; string[i] != 0x00; i++) {
        char c = string[i];
        if (c != delim) {
            returner[loc][innerLoc] = c;
            innerLoc++;
        } else {
            print ("a string was ");
            println (returner[loc]);
            innerLoc = 0;
            loc++;
        }
    }
    print ("the first string was ");
    println (returner[0]);
    return (char**)returner;
}

I am asking a question about how to write a specific function in C++ freestanding mode.


Solution

  • void split(const char* str, const char d, char** into)
    {
        if(str != NULL && into != NULL)
        {
            int n = 0;
            int c = 0;
            for(int i = 0; str[c] != '\0'; i++,c++)
            {
                into[n][i] = str[c];
                if(str[c] == d)
                {
                    into[n][i] = '\0';
                    i = -1;
                    ++n;
                }
            }
        }
    }
    

    I'm allocating using calloc to get rid of garbage characters.

    EDIT: You should allocate the pointers inside the char** before writing to them.

    void allocarr(char** pointers, int bytes, int slots)
    {
        int i = 0;
        while(i <= slots)
        {
            pointers[i] = (char*)calloc(1, bytes);
            ++i;
        }
    }
    

    ...

    char** sa = (char**)malloc(50*sizeof(char*));
    allocarr(sa, 512, 50);
    split("Hello;World;", ';', sa);
    puts(sa[0]);