简体   繁体   中英

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 .

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. Nowhere do I pass it as a void * or anything like that.

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:

#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. Now, it turns out that malloc returns a void * , from which we deduce that handles is still a void * after assignment.

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. But if you grok what the MISCTYPE is, I bet you'll find the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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