取消引用void指针到指针数组 [英] De-referencing void pointer to a pointer array
问题描述
我正在使用学校提供给我的线程库,无法理解如何将指针数组的引用传递给方法,或者说,我在解引用和使用指针数组时遇到了麻烦.
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;
}
我正在创建一个指向Foo对象的指针,并将其通过引用传递给运行MyFunction的线程,该线程接受一个void指针作为其参数.然后,MyFunction将"arg"强制转换为Foo指针,并对其取消引用以获取原始对象.
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.
当我想传递一个Foo指针数组而不是一个数组时,就会出现我的问题:
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;
}
推荐答案
将 MyFunction(& barGroup);
替换为 MyFunction(barGroup);
(从而传递指针)指向第一个元素,而不是指向整个数组的指针),然后使用嵌套的指针:
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);
然后,您可以简单地使用 barGroup [0]
, barGroup [1]
和 barGroup [2]
.
Then you can simply use barGroup[0]
, barGroup[1]
and barGroup[2]
.
这篇关于取消引用void指针到指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!