Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mental model for void* and void**?

Note: I'm a experienced C++ programmer, so I don't need any pointer basics. It's just that I never worked with void** and have kind of a hard time getting my mental model adjusted to void* vs. void**. I am hoping someone can explain this in a good way, so that I can remember the semantics more easily.

Consider the following code: (compiles with e.g. VC++ 2005)

int main() {
  int obj = 42;
  void* ptr_to_obj = &obj;
  void* addr_of_ptr_to_obj = &ptr_to_obj;
  void** ptr_to_ptr_to_obj = &ptr_to_obj;
  void* another_addr = ptr_to_ptr_to_obj[0];
  // another_addr+1; // not allowed : 'void*' unknown size
  ptr_to_ptr_to_obj+1; // allowed
}
like image 204
Martin Ba Avatar asked Apr 08 '11 07:04

Martin Ba


2 Answers

void* is a pointer to something, but you don't know what. Because you don't know what it is, you don't know how much room it takes up, so you can't increment the pointer.

void** is a pointer to void*, so it's a pointer to a pointer. We know how much room pointers take up, so we can increment the void** pointer to point to the next pointer.

like image 84
Simon Nickerson Avatar answered Sep 19 '22 15:09

Simon Nickerson


A void* points to an object whose type is unknown to the compiler.

A void** points to a variable which stores such a void*.

like image 39
fredoverflow Avatar answered Sep 21 '22 15:09

fredoverflow