简体   繁体   English

当用类型声明指针时,如何解除引用'void *'?

[英]How can this be dereferencing ‘void *’ when the pointer was declared with a type?

I'm trying to make an array with file-level or global scope whose size is determined at runtime. 我正在尝试创建一个文件级或全局范围的数组,其大小在运行时确定。 Various articles like this one suggest this pattern for such a dynamic array: 这样的各种文章建议这种动态数组的模式:

static MISCTYPE *handles;
static int nthreads;

int main(int argc, char **argv) {
    // nthreads set from from argv
    handles = malloc(nthreads * sizeof(MISCTYPE));
    for(i = 0; i < nthreads; i++) {
        handles[i] = miscfunction();
    ...
    free(handles);
    return 0;
}

int otherfunction(...) {
    for(i = 0; i < nthreads; i++) {
        handles[i] = miscfunction();
    ...
}

However, everywhere I use the pointer like an array (ie handles[i] ) the compiler says warning: dereferencing 'void *' pointer and then error: invalid use of void expression . 但是,无论我在哪里使用像数组一样的指针(即handles[i] ),编译器都会warning: dereferencing 'void *' pointer然后error: invalid use of void expression

But it's not a void pointer! 但它不是一个无效的指针! It definitely has a type (MISCTYPE in this pseudocode), and re-casting it into the same type doesn't stop the errors. 它肯定有一个类型(此伪代码中的MISCTYPE),并将其重新转换为相同的类型不会阻止错误。 Nowhere do I pass it as a void * or anything like that. 我没有把它作为一个void *或类似的东西传递给我。

What's going on here? 这里发生了什么? More importantly, what can I do about it? 更重要的是,我能做些什么呢?

Yeah, there must be something goofy with MISCTYPE because the example below works fine: 是的,MISCTYPE肯定会有一些愚蠢的东西,因为下面的例子工作正常:

#include <stdio.h>
#include <stdlib.h>

static int *handles;

int main(int argc, char **argv)
{

    int i = 0;
    handles = malloc(20 * sizeof(int));
    for(i = 0; i < 20; i++) {
        handles[i] = i;
    }

    free(handles);
    return 0;
}

Okay, to start with, if the compiler tells you handles is a void * , you should believe it. 好的,首先,如果编译器告诉你handlesvoid * ,你应该相信它。 Now, it turns out that malloc returns a void * , from which we deduce that handles is still a void * after assignment. 现在,事实证明, malloc返回void * ,从中我们推断, handles仍然是一个void *分配之后。

From this we may deduce that the assignment isn't doing what you think it is. 由此我们可以推断出任务没有按照你的想法进行。 At this point we have to ask "so what is MISCTYPE ", and we, using the code you've posted, can't deduce that. 在这一点上,我们不得不问“那么什么是MISCTYPE ”,而且我们使用您发布的代码无法推断出这一点。 But if you grok what the MISCTYPE is, I bet you'll find the answer. 但如果你了解MISCTYPE是什么,我打赌你会找到答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM