Tuesday 3 June 2014

void pointer

void *

Sometimes we know we want a pointer, but we don't necessarily know or care what it points to. The C/C++ language provides a special pointer, the void pointer, that allows us to create a pointer that is not type specific, meaning that it can be forced to point to anything.Why is this useful? One common application of void pointers is creating functions which take any kind of pointer as an argument and perform some operation on the data which doesn't depend on the data contained. A function to "zero-out" memory (meaning to turn off all of the bits in the memory, setting each byte to the value 0) is a perfect example of this.

void memzero(void *ptr, size_t len)
{
 for(; len>0; len--) {
  *(char *)ptr = 0;
 }
}
This function takes a pointer to any piece of memory, meaning that we can pass in any kind of pointer we want, and the number of bytes to zero out. It then walks along the memory zeroing out each byte. Without void pointers, it would be more difficult to write a generic function like this.

Other example
void increaseChar (char* charData)
{
    ++(*charData);
}

void increaseInt (int* intData)
{
    ++(*intData);
}

int main ()
{
  char a = 'x';
  int b = 1602;
  increaseChar (&a);
  increaseInt (&b);
  cout << a << ", " << b << endl;
  string str;
  cin >> str;
  return 0;
}

No comments:

Post a Comment