简体   繁体   中英

Can I use a void pointer in C as an array?

I tried doing this in C and it crashes:

int nValue=1;   
void* asd;  
asd[0]=&nValue;

With the following error:

*error C2036: 'void**' *: unknown size  
error C2100: illegal indirection*

Can I use a void pointer in C as an array?

And if I can, what is the correct way to do so?

Can I use a void pointer in C as an array?

Nope. You can convert to and from void* , but you cannot derference it, and it makes sense when you think about it.

It points to an unknown type, so the size is also unknown. Therefore, you cannot possibly perform pointer arithmetic on it (which is what asd[0] does) because you don't know how many bytes to offset from the base pointer, nor do you know how many bytes to write.

On a side note, asd (likely) points to invalid memory because it is uninitialized. Writing or reading it invokes undefined behavior.

you can write like this:

int main()
{
    int iv = 4;
    char c = 'c';
    void *pv[4];
    pv[0] = &iv;
    pv[1] = &c;

    printf("iv =%d, c = %c", *(int *)pv[0], *(char *)pv[1]);
    return 0;
}

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