0

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?

6
  • 2
    void * cannot be dereferenced but it can be converted between any pointer type. That being said, you never even initialize asd here... Commented Sep 14, 2012 at 0:01
  • What are you getting out of doing this? Commented Sep 14, 2012 at 0:03
  • Not sure what you're expecting that to do. You can make an array of void pointers if you declared as void* asd[5]; Commented Sep 14, 2012 at 0:05
  • @chris Im trying to debug a library which is giving me erros and I wanted to know if this is even possible. Commented Sep 14, 2012 at 0:09
  • @oldrinb so with what can it be initialized? with a string for instance and then use the brackets to modify each caracter? Commented Sep 14, 2012 at 0:10

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Make sure you state sizeof(void) is undefined ;-)
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.