Possible Duplicate:
What is a void pointer and what is a null pointer?
I often see code which resembles something like the following:
void * foo(int bar);
What does this mean? Does it mean that it can return anything? Is this similar to dynamic
or object
in C#?
A void* can point to anything (it's a raw pointer without any type info).
A
void*
pointer is used when you want to indicate a pointer to a hunk of memory without specifying the type. C'smalloc
returns such a pointer, expecting you to cast it to a particular type immediately. It really isn't useful until you cast it to another pointer type. You're expected to know which type to cast it to, the compiler has no reflection capability to know what the underlying type should be.A
void*
does not mean anything. It is a pointer, but the type that it points to is not known.It's not that it can return "anything". A function that returns a
void*
generally is doing one of the following:operator new
andmalloc
return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE:void
.This construct is nothing like
dynamic
orobject
in C#. Those tools actually know what the original type is;void*
does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.And on a personal note, if you see code that uses
void*
's "often", you should rethink what code you're looking at.void*
usage, especially in C++, should be rare, used primary for dealing in raw memory.Void is used as a keyword. The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type:
General Syntax:
A void pointer can point to objects of any data type:
However, because the void pointer does not know what type of object it is pointing to, it can not be dereferenced! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.
Source: link