Help in void pointers

In the tutorial about pointers i didnt understand the code for void pointers
what is pchar=(char*)data doing? can you explain me?



/ 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;
}

what is pchar=(char*)data?
can you explain me line by line especially the pchar=(char*)data part

and when im using const char * terry = "Hello";
and im using cout<<terry; IM NOT GETTING THE ADDRESS ,WHY??
HELP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

void increase (void* data, int psize) // data is a void pointer that can point to objects of any type.
{
  if ( psize == sizeof(char) ) // if the input psize matches size of char
  { 
     char* pchar;           // pchar is a pointer to char
     pchar=(char*)data; // make data a pointer to char (explicit casting) and make pchar also point to the same data.
     ++(*pchar);           // increase the value that is pointed to by pchar
   }
   else if (psize == sizeof(int) ) // if the input psize matches size of int
   { 
      int* pint;            // pint is a pointer to int
      pint=(int*)data;  // make data a pointer to int (explicit casting) and make pint also point to the same data.
      ++(*pint);  // increase the value that is pointed to by pint
   }
 }

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


To answer your second question, the following link would help.
http://stackoverflow.com/questions/501816/why-does-cout-print-char-arrays-differently-from-other-arrays
C-style conversion of the type of the pointer from void to char and assignment of the value to another pointer variable.

cout has overloaded operator << for printing const char * like it is a string (like it usually is).
The part to the right of the assignment operator, (char*)data, is called a "type cast". What this is doing is telling the program to treat the variable, data, as a pointer to a char regardless of what it actually is.

EDIT: Note that it does not actually change the data type of 'data'. Any other time you address this variable in the code it will be a void pointer unless you cast it again.
Last edited on
Topic archived. No new replies allowed.