3

When something is cast to void, then the value becomes NULL. However, why does a void * point to any data type? Shouldn't a void pointer just be useless?

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
  • 4
    *When something is cast to void, then the value becomes NULL.* Needs proof/citation ;-) – P.P Mar 18 '14 at 22:34
  • A `void` pointer is far from useless. Unlike the "typed" pointers, it lets the programmer legitimately decide what it points to. However, the legitimacy of that is, of course, totally up to the programmer. – Daniel Kamil Kozar Mar 18 '14 at 22:35
  • casts to not change values, just how they are interpreted in that context... it can invoke an instruction on the value of the variable to change it to a double, for instance but the original value will not be changed. – Grady Player Mar 18 '14 at 22:46
  • @BlueMoon I guess there is confusion between `void` and `void*` here. – user2802841 Mar 18 '14 at 22:47
  • http://stackoverflow.com/questions/689677/casting-unused-return-values-to-void It says that casting to void will throw the value out – lost_in_the_source Mar 18 '14 at 22:55
  • @EdwardKarak I see you still don't know the difference between `void` and `void *`. `void` is the lack of a variable type. When used with a function, it indicates that the function has no variable type (and therefore does not return any information). When used with a pointer, it indicates that the pointer has no variable type (and therefore does not know *what type of variable is in the memory address it points to*). The difference is substantial. – ciphermagi Mar 18 '14 at 23:03
  • "*why does a void\* point to any data type*" it actually does **not**, and that is what makes it special. – alk Mar 19 '14 at 07:30
  • "*When something is cast to `void` ...*" you probably wanted to write "*When something is cast to `void *` ...*". – alk Mar 19 '14 at 07:34

3 Answers3

8

A void pointer is a pointer to anything. It is a generic pointer that doesn't have a particular type. It can also have the value NULL in which case it doesn't point to anything. To use a void pointer, you have to keep track of what it actually points to and when you are going to use it, you must cast it to the appropriate type.

They can be dangerous, because if you cast it to the wrong type, it will result in undefined behavior at runtime.

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
3

When something is cast to void, then the value becomes NULL.

Not true. Nothing happens to the pointed data.

Shouldn't a void pointer just be useless?

A void pointer is the closest thing C has to a "generic type" and is very useful in that it allows things like somewhat generic functions, somewhat generic containers etc.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
2

void * is a generic object pointer. Note that there is no generic function pointer.

You can convert any object pointer value to void * and back without loss of value.

ouah
  • 142,963
  • 15
  • 272
  • 331