如何正确使用无效**指针? [英] how to use void ** pointer correctly?
问题描述
我想使用双无效
指针,但我对使用一个有点困惑。
我有一个结构
包含无效**
阵列。
I am trying to use a double void
pointer but I am a little bit confused about the usage.
I have a struct
that contains a void **
array.
struct Thing{
void ** array;
};
struct Thing * c = malloc (sizeof(struct Thing));
c->array = malloc( 10 * sizeof(void *) );
所以,如果我想在不同的对象分配给每个指针,并尝试检索值
So If I want to assign a different object to each pointer and try to retrieve the value
// Option 1
*(c->array + index) = (void *) some_object_ptr;
// Option 2
c->array[index] = (void *) some_object_ptr;
那么,我还有一个功能,让(无效*)的项目
,它指向每一个细胞,而不是 some_object_ptr
。
then, I have another function that gives (void *) item
that points to each cell, not the some_object_ptr
.
如果我想找回它通过 some_object_ptr
,结果指着值
我应该做的。
If I want to retrieve the value which pointed to by some_object_ptr
,
should I do
function return type is 'void *' and takes argument 'void *'
// Option 3
return (void**) item
// Option 4
return *((void**)item)?
奇怪的是,当我用数组的数组下标方法我不能使用选项4,唯一的选择3;当我用 *(C-GT&;阵列+指数)
我只能用opt.4。而不是opt.3。 ..
the weird thing is that when I used array the array subscript method I couldn't use option 4, only option 3; and when I used *(c->array + index)
I could only use opt.4. and not opt.3. ..
谁能告诉我这件事?如果我做出任何无效的假设,那么请你指正?
Can anyone please tell me about this? If I am making any invalid assumptions, then could you please correct me?
推荐答案
A 无效**
只是一个指针指向内存的指针与未指定类型。您只能提领一次(因为你不能取消引用无效*
)。但是,除此之外,它基本上是像任何其他指针类型。如果它可以帮助你,想用同样的方式,你会与为int *
。
A void **
is just a pointer to a pointer to memory with an unspecified type. You can only dereference it once (since you can't dereference a void *
). However, apart from that, it is basically like any other pointer type. If it helps you, think of it the same way as you would with int *
.
所以,在你的具体情况,我们有:
So, in your specific situation, we have:
void** array;
int arrayLen = 10;
array = (void**)malloc(arrayLen * sizeof(void*));
some_type_t* some_object_ptr;
// The following two assignment are equivalent since in C,
// array[index] <=> *(array + index)
array[index] = (void*)some_object_ptr;
*(array + index) = (void*)some_object_ptr;
然后阵列
是指向整个阵列,而 *阵列
是一个指向第一个元素,因为它相当于数组[0]
。
Then array
is a pointer to the whole array, while *array
is a pointer to the first element, since it is equivalent to array[0]
.
这篇关于如何正确使用无效**指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!