void pointers

hey guys, i was reading the tutorials and came across this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// increaser
#include <iostream>
using namespace std;

void increase (void* data, int psize)
{
  if ( psize == sizeof(char) )
  { char* pchar; pchar=(char*)data; ++(*pchar); }
  else if (psize == sizeof(int) )
  { int* pint; pint=(int*)data; ++(*pint); }
}

int main ()
{
  char a = 'x';
  int b = 1602;
  increase (&a,sizeof(a));
  increase (&b,sizeof(b));
  cout << a << ", " << b << endl;
  return 0;
}


found here http://www.cplusplus.com/doc/tutorial/pointers.html under 'void pointers'.

what i dont understand is this part:
pchar=(char*)data;

and

pint=(int*)data;

why where they used?

wouldnt

pchar=*data;
pint=*data;

have worked? why is that put there?


edit:

im guessing its because the pointer is void so the (int*) and (char*) tells it what sort of thing its pointing to or something?
Last edited on
But in exchange they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it.
Topic archived. No new replies allowed.