Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.
share|improve this question

1 Answer 1

up vote 3 down vote accepted

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 *));
share|improve this answer
    
Awesome! That works, but I thought myTerms[c] = allTerms[i] would make a copy and not a pointer. Why isn't it a copy? –  HZN Nov 14 '13 at 7:52
    
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. –  paddy Nov 14 '13 at 20:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.