2

char *, as the original generic pointer, does its job well. As I know, a void * can do nothing more than a char *. What's more, doing arithmetic with void * is not supported by the standard, which is somewhat error-prone.

So why do we need a void * type in C? And when should we use it, rather than char *?

Community
  • 1
  • 1
nalzok
  • 14,965
  • 21
  • 72
  • 139
  • 2
    for implicit converversions, and generic object types? ie psuedo object oriented C stuff – Grady Player Feb 25 '16 at 04:38
  • 4
    You can't dereference a `void*`, so it prevents you from doing some stupid things. – Cornstalks Feb 25 '16 at 04:43
  • What makes you say `char*` is the "original" pointer? – Adam Feb 25 '16 at 04:46
  • 1
    `char *` makes a lot of assumptions about what is being pointed to. Those assumptions tend to match the view that most people have of memory today, but that doesn't make those views universal. `void *` makes no such assumptions. – Adam Feb 25 '16 at 04:48
  • 3
    `doing arithmetic with void * is not supported by the standard, which is somewhat error-prone` On the contrary, it catches at compile time potentially bogus arithmetic that would otherwise bomb at runtime. – dxiv Feb 25 '16 at 04:48
  • 2
    voting to reopen, I don't think this is an opinion-based question – M.M Feb 25 '16 at 05:27

1 Answers1

3

a void * can do nothing more than a char *

I'm not sure about which can do more things than another but I'm sure that void* can do his own jobs which char * (or any other type of pointer) cannot.

void* is known as a generic pointer. Generic pointer:

  • Can hold any type of object pointers
  • Cannot be dereferenced
  • Especially useful when you want a pointer to point to data of different types at different times

And if you try hard to make char* do something that void* can do, it may possible but will lead to assumption.

If even the compiler does not inform an error or at least a warning about incompatible type, we still don't want to see this kind of code:

//hi guys, the argument is char* type 
//but you still can pass any other pointer types 
//don't worry!
void func(char * p) {
    ...
}

We just need this:

//this comment is not need, right?
//you know that you can pass any pointer types
void func(void* p) {
    ...
}
Van Tr
  • 5,889
  • 2
  • 20
  • 44
  • 1
    "Generic pointer Can hold any type of pointers" : standard C forbids assignment between function pointer and `void *`. So it's more accurate to say that "generic pointer can hold any type of **object** pointers". – candide Apr 19 '16 at 20:09