问题
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