0

I'm using a threading library given to me at school and having trouble understanding how to pass a reference of an array of pointers to a method, or rather, I'm having trouble de-referencing and using the pointer array.

The situation that I (believe I) understand is this:

int main(void)
{
    Foo* bar = new Foo();

    // Passing instance of Foo pointer by reference 
    CThread *myThread = new CThread(MyFunction, ACTIVE, &bar);

    return 0;
}

UINT __stdcall MyFunction(void *arg)
{
    Foo* bar = *(Foo*)(arg); 

    return 0;
}

I'm creating a pointer to a Foo object and passing it by reference to a thread running MyFunction, which accepts a void pointer as its argument. MyFunction then casts "arg" to a Foo pointer and de-references it to get the original object.

My problem arises when I want to pass an array of Foo pointers instead of just one:

int main(void)
{
    Foo* barGroup[3] = 
    {
        new Foo(),
        new Foo(),
        new Foo()
    };

    // Passing instance of Foo pointer by reference 
    CThread *myThread = new CThread(MyFunction, ACTIVE, &barGroup);

    return 0;
}

UINT __stdcall MyFunction(void *arg)
{
    // This is wrong; how do I do this??
    Foo* barGroup[3] = *(Foo[]*)(arg); 

    return 0;
}
Ian
  • 3
  • 3

1 Answers1

4

Replace MyFunction(&barGroup); with MyFunction(barGroup); (thus passing a pointer to the first element instead of a pointer to the entire array) and use a nested pointer:

Foo** barGroup = (Foo**)(arg); 

Then you can simply use barGroup[0], barGroup[1] and barGroup[2].

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • So let's see if I understand; I'm passing a pointer to the first element because arrays in C++ are pointers? The casting part I don't understand as much. I'm casting to a pointer to a pointer, is that because my original object was an array of pointers, which is actually a pointer to a pointer? – Ian Mar 07 '12 at 20:44
  • **Arrays are not pointers**, but they can silently be converted to pointers. If you want to dig deeper, read our [FAQ on arrays](http://stackoverflow.com/questions/4810664/). – fredoverflow Mar 07 '12 at 20:51
  • Thanks, the FAQ looks very helpful! – Ian Mar 07 '12 at 21:06