Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to void in C++?

I'm reading some code in the Ogre3D implementation and I can't understand what a void * type variable means. What does a pointer to void mean in C++?

like image 547
tunnuz Avatar asked Jan 04 '09 18:01

tunnuz


People also ask

Can a pointer point to void?

A void pointer is a pointer that can point to any type of object, but does not know what type of object it points to. A void pointer must be explicitly cast into another type of pointer to perform indirection. A null pointer is a pointer that does not point to an address. A void pointer can be a null pointer.

What is void pointer example?

Example of pointer in Cint a=5; int* point = &a; // pointer variable point is pointing to the address of the integer variable a! int a=5; int* point = &a; // pointer variable point is pointing to the address of the integer variable a!

Can you free a void * in C?

Not only is it OK to free() a void * value, by definition, all free() ever sees is a void * , so technically, everything freed in C is void * :-) @Daniel - If you ask me, it should be struct foo *p = malloc(sizeof *p)); but what do I know?


2 Answers

A pointer to void, void* can point to any object:

int a = 5;
void *p = &a;

double b = 3.14;
p = &b;

You can't dereference, increment or decrement that pointer, because you don't know what type you point to. The idea is that void* can be used for functions like memcpy that just copy memory blocks around, and don't care about the type that they copy.

like image 189
Johannes Schaub - litb Avatar answered Oct 13 '22 01:10

Johannes Schaub - litb


It's just a generic pointer, used to pass data when you don't know the type. You have to cast it to the correct type in order to use it.

like image 35
Chuck Avatar answered Oct 13 '22 00:10

Chuck