De-referencing void pointer to a pointer array

≯℡__Kan透↙ 提交于 2021-02-16 15:39:25

问题


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;
}

回答1:


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



来源:https://stackoverflow.com/questions/9608433/de-referencing-void-pointer-to-a-pointer-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!