I understand that a pointer is a variable that hold an address, so why
we have to specify the type of variable of the pointer, for example:
int * age ;
float * price ;
etc.
If a pointer holds an address, why do we need to specify int, float
and other for a pointer?
It is necessary because if you want to write something to the memory area
the pointer points to, then the computer needs to know, how many bytes do
you want to write. The pointer by itself does not contain any information
about the length of the memory area allocated.
Of course, there is also a possibility for non-type pointers - they are
defined as of type "void *". But if you assign something to the area they
point to, then you *must* cast the types:
////////////////////////////////////////////////////////////
void *pointer; //Let's create a new void pointer
pointer=new int[6]; //Allocate memory for 6 integers and store the pointer
//to the beginning of the array in "pointer"
((int *)pointer)[3]=654; //Let the third element of the array be 654
//Note the typecasting!
//Otherwise the computer wouldn't know exactly, where do you
//want to write the number.
//If, for instance, we would have an array of char's, then the third
//element would be only the 3. byte from the "*pointer".
//But for int's it is "3*sizeof(int)"'s byte (sizeof(int) is normally
//4. or 2. on older compiler or a 16-bit architecture)
// Now do anything you like
delete[] (int *)pointer; //No let's free the array, again note the casting!
pointer=new char; //Now let's use *pointer as a single character
*((char *)pointer)='a'; //Or anything you like
delete (char *)a; //And finally let's free the memory (because we have a
//single variable at "*pointer", we now use "delete", not "delete[]"
/////////////////////////////////////////////////////////////