Reputation: 23978
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++?
Upvotes: 11
Views: 8277
Reputation: 8418
Building off my prior posting...
ATTENTION: All memory addresses here are fictional. I'm just making them up to illustrate a point.
Given:
int data[] = {10,11,12};
We now have:
0xffff0000-0xffff0003 with a value of (int)(10)
0xffff0004-0xffff0007 with a value of (int)(11)
0xffff0008-0xffff000b with a value of (int)(12)
(I'm not going to get into big-endian vs little-endian byte ordering here.)
If we have:
int * p = data;
We now have another memory location somewhere else, say:
0xaaaa0000-0xaaaa0003 with a value of (int*)0xffff0000
We can use p[1] [or *(p + 1)] to refer to *(int*)(0xffff0004) [=11] as sizeof(int)=4 and 0xffff0000+sizeof(int) = 0xffff0004.
If we have:
void * v = data;
We now have another memory location somewhere else, say:
0xbbbb0000-0xbbbb0003 with a value of (void*)0xffff0000.
However, void doesn't have any associated sizeof() information. We can't increment or decrement the pointer. We can't dereference to access the data stored in 0xffff0000. We can only utilize the value as a raw memory address.
If we want to use the data stored in (void*)0xffff0000, we first need to cast it to an appropriate type.
That said, (void *) is still quite useful as a means of passing addresses to arbitrary data structures around. For instance, memset(). It doesn't matter whether I'm zero'ing out a struct tm or a struct sockaddr. We just need a pointer to the struct and its size.
(This should go without saying, but... Beware using memset to zero out a class instance and, in doing so, overwriting the virtual pointer table.)
Upvotes: 1
Reputation: 506847
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.
Upvotes: 39
Reputation: 38130
It's a pointer to anything -- just a chunk of memory that you can play with -- might be an object, might be a char. You have to cast to do anything useful with it.
Upvotes: 2
Reputation: 237010
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.
Upvotes: 4
Reputation: 74250
It's a raw pointer to a spot in memory. It doesn't allow any pointer arithmetic like char * or int *.
Here's some examples of usage
http://theory.uwinnipeg.ca/programming/node87.html
Upvotes: 3