/************************* VOIDPT.CPP *****************************************
* Example of pointer type conversion                               1998-09-02 *
*                                                                   Agner Fog *
*                                                                             *
* A void pointer can point to any type of data. You have to convert it to     *
* the type of data it points to before you can use it. The switch statement   *
* in ReadInput converts the pointer 'address' to the desired type.            *
******************************************************************************/
#include <iostream.h>
#include <string.h>
#include <stdlib.h>

// This function reads data from keyboard into memory pointed to by address.
// Type defines the type of data that address points to:
// 1 = integer,
// 2 = float,
// 3 = string.
void ReadInput (int DataType, void * address)
{
   char buffer[30];
   // read from keyboard into string buffer:
   cin.getline(buffer, sizeof(buffer));

   switch (DataType)
   {
   case 1:  // integer
      *(int*)address = atoi(buffer);
      break;

   case 2:  // float
      *(float*)address = atof(buffer);
      break;

   case 3:  // string
      strcpy((char*)address, buffer);
      break;
   }
}


void main () 
{
   float x;
   cout << "\nEnter number ";
   ReadInput (2, &x);

   cout << "\nsquare = " << x*x;
}

// Warning: strange things will happen if you convert a pointer to a different
// type than the data it actually points to. If x were declared as a double
// instead of float in the example above then you would get a crazy result!
