Search code examples
carrayspointersmultidimensional-arraydynamic-memory-allocation

Dynamically Creating an Array of Char Pointers in C


I am trying to make a function that dynamically adds the pointers of selected words from an input array (allTerms) to an array that it will eventually return (myTerms). The pointers point to various words in the allWords array, and based on a function (isTermNeeded) words are chosen to be included (as pointers to allWords). How do I assign pointers to myTerms and allocate enough space for it to work?

Here is the snippet I'm having trouble with:

myTerms    = (char **)realloc(myTerms, (c+1)*sizeof(char *));
myTerms[c] = allTerms[i];

And here is the full function:

char **getMyTerms(char **allTerms, char info[])
{
    int     i   =   0,
            c   =   0; // amount of terms selected

    char **myTerms; // array of selected terms

    while (allTerms[i])
    {
        if (isTermNeeded(allTerms[i], info))
        {
            myTerms     =   (char **)realloc(myTerms, (c+1)*sizeof(char *));
            myTerms[c]  =   &allTerms[i];

            c++;
        }

        i++;
    }

    return myTerms;
}

And here is the warning I've been getting:

term.c:95:15: warning: incompatible pointer types assigning to 'char *' from 'char **'; remove & [-Wincompatible-pointer-types]
                        myTerms[c]      =       &allTerms[i];
                                        ^       ~~~~~~~~~~~~
1 warning generated.

Solution

  • It should be this:

    myTerms[c] = allTerms[i];
    

    Also, make sure you initialise myTerms, or you may have dramas when you run realloc:

    char **myTerms = NULL;
    

    In C, you shouldn't cast the result from realloc either:

    myTerms = realloc(myTerms, (c+1)*sizeof(char *));