1

Noob alert;

I'm learning C and came across void*

What I don't understand is that, if I'm referencing an int variable with a void pointer, why can't I simply dereference ALSO with a void pointer. And if I want to, I have to typecast.

so why would I ever want to use void* to begin with If I'm always going to typecast it with, let's say an Integer. And why not just use int* all the time

Code:

 int main()
 {
    int i = 10;
    void* p = &i;

    printf("%i", *(int*)p); // typecasting before dereferencing
    return 0;
 }
Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34
  • Can you show some code? most likely, `void *` is being used as a placeholder. – Sourav Ghosh Jul 17 '18 at 12:37
  • If you have a pointer to `void`, how would *compiler* know what it is *really* pointing at? The compiler can't know that, only you as the programmer can know that. – Some programmer dude Jul 17 '18 at 12:38
  • As for why? A common thing these days with large multi-core processors is *threads*. And most thread-creation function can pass a pointer to *something* to the function running the thread, but the thread-creation function don't know *what* you want to pass a pointer to, so it have to use the generic "any pointer" `void *`. – Some programmer dude Jul 17 '18 at 12:40
  • 1
    Or how about the memory allocation function [`malloc`](http://en.cppreference.com/w/c/memory/malloc)? It allocates a chumk of memory and returns a pointer to the first byte of the memory. But it doesn't know what you want to use the memory for, so it returns a generic any pointer with the type `void *`. Then it's up to you to use that pointer by assigning it to a variable of the correct type. – Some programmer dude Jul 17 '18 at 12:41
  • @Someprogrammerdude hi, thanks for you comment. Can you expand on the why part? Also, if you could provide me references to learn more about it? Thanks for your time – Sumit Wadhwa Jul 17 '18 at 12:42
  • 1
    In general, you are exactly right. In general, if you want a pointer to type *T*, you should use a pointer to type *T*. Too much code uses `void *` unnecessarily, leading to confusion, unportability, and bugs. Don't assume from the bad code you see that passing void pointers around, and casting them all over the place, is the right thing to do. It's not. (There are *specific* situations where you need `void *`, of course -- the canonical example is `malloc` -- but those situations are, well, specific.) – Steve Summit Jul 17 '18 at 13:52

0 Answers0