Search code examples
cpointersmallocc-stringspointer-to-pointer

How do I convert a char * string into a pointer to pointer array and assign pointer values to each index?


I have a char * that is a long string and I want to create a pointer to a pointer(or pointer array). The char ** is set with the correct memory allocated and I'm trying to parse each word from the from the original string into a char * and place it in the char **.

For example char * text = "fus roh dah char **newtext = (...size allocated) So I'd want to have:

char * t1 = "fus", t2 = "roh", t3 = "dah";
newtext[0] = t1;
newtext[1] = t2;
newtext[2] = t3;

I've tried breaking the original up and making the whitespace into '\0' but I'm still having trouble getting the char * allocated and placed into char**


Solution

  • Assuming that you know the number of words, it is trivial:

    char **newtext = malloc(3 * sizeof(char *));   // allocation for 3 char *
    // Don't: char * pointing to non modifiable string litterals
    // char * t1 = "fus", t2 = "roh", t3 = "dah";
    char t1[] = "fus", t2[] = "roh", t3[] = "dah"; // create non const arrays
    
    /* Alternatively
    char text[] = "fus roh dah";    // ok non const char array
    char *t1, *t2, *t3;
    t1 = text;
    text[3] = '\0';
    t2 = text + 4;
    texts[7] = '\0';
    t3 = text[8];
    */
    newtext[0] = t1;
    newtext[1] = t2;
    newtext[2] = t2;