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;
}
7
  • Why are you passing the addressof a pointer? Commented Mar 7, 2012 at 20:21
  • You are not passing by reference. You are passing a pointer to a pointer to an object. Also, why are you using void*? Commented Mar 7, 2012 at 20:21
  • 2
    *(Foo*(*)[3]) But why? Commented Mar 7, 2012 at 20:23
  • using void*s like this, and in almost every case, is notoriously bad practice. Commented Mar 7, 2012 at 20:25
  • Why are you using void* and not the real type? Commented Mar 7, 2012 at 20:26

1 Answer 1

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].

Sign up to request clarification or add additional context in comments.

3 Comments

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?
Arrays are not pointers, but they can silently be converted to pointers. If you want to dig deeper, read our FAQ on arrays.
Thanks, the FAQ looks very helpful!

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.