raj_duttaphookan wrote:
> main( )
> {
> int x;
> ..............;
> ..............;
> int getValue(&x);//the address of x is passed on to the calling
> //function.
> ..............;
> }
>
>
> int getValue(pointer p) //here the address shall come to p
> {
> return *p; // here it is simply returning the value at the
> //address which is contained in p. And since it
> //was already defined in main( ) as int x, so
> //obviously it shall return an int.
> }
>
What happens if you call getValue() from a different function? At that
point the computer cannot determine to what type the variable points.
Defining these types helps the compiler perform conversions as
necessary. By defining a pointer as e.g. int*, it knows that (typically)
it is a four byte signed integer. If you attempt to store this in a
float, it knows to run that value through a conversion function first.
If you do not have a pointer type defined, it would have no choice but
to interpret the bits as a floating point number, which is stored in a
completely separate way from integers.
#include <iostream>
int main(int argc, char *argv[]) {
int x = 3497545;
int *p = &x;
std::cout << "Printing an integer: " << *p << std::endl;
std::cout << "Printing some random float that is nothing like the int
above: "
<< *((float *) p) << std::endl;
return 0;
}
Run this program and you will understand why pointers are defined as
pointing to specific types.
--
John Gaughan