T1
, we can override that and
convince the compiler that the pointer points to something of type
T2
.
Let us consider the following example:
void *pVoid; int *pInt; float *pFloat;
First, we can have the following assignment statement:
pVoid = pInt;
This works just fine because in C, any pointer can become a void pointer with no explicit casting. However, the following assignment generates an error:
pInt = pVoid;
This is because this operation is potentially dangerous. However, assuming that we know what we are doing, we can accomplish this using type casting:
pInt = (int *)pVoid;
Here, the (int *)
type cast operator tells the compiler that
``the programmer seems to know what this operation is about, go ahead
and assume the type of what pVoid
points to is indeed
an integer.''
You can probably imagine that the following will generate an error:
pFloat = pInt;
This is because the float
type and int
type have different
ways to represent numbers. However, we can force the compiler to allow
this to happen:
pFloat = (float *)pInt;
In fact, you can cast the point-to type of a pointer to anything with type casting!
Copyright © 2006-08-30 by Tak Auyeung