0

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.

1 Answer 1

4

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 *));
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! That works, but I thought myTerms[c] = allTerms[i] would make a copy and not a pointer. Why isn't it a copy?
It's just a pointer (integer referring to a memory location) that you are copying into another array. When you copy a pointer, think of it as writing down a phone number for someone. It doesn't matter how many have people your phone number - you still have just the one phone.

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.