Saturday, June 30, 2007

Typecasting with Pointers!

What is tpecasting?
Typecasting, as its name suggests, is changing a variable's type into another.

How do we do it in C?
In C, typecasting can be automatic as well as manual. Automatic in a way that a variable of a narrower type can be converted into one of a wider one just by mere assignment .
Ex:
int a;
double q,m;
a=q;//a is converted into one of double tpes directly by assignment.
m=sqrt(a);//sqrt can take only doubles as auguments.

It pays to note that q=a, does not do the opposite, because of the earlier specifie reason.(Narrower to wider)

Now, we move on to an interesting question.
How do we change the type of pointers.

Ex: How do we convert an integer ptr to a double ptr.

My guess is that it can be done using the malloc() function.

int *p;
p=(double *) malloc(sizeof(double));

now p will point to a double. Malloc takes the sizeof a data type as an augument and returns a void ptr which can be casted using the "(type)" feature...

Having written this much, i have a doubt if the foll code will do the same operation...Pls comment if i am wrong...

int *p,i;
double q;
p=&i;
i=q;

now is p now a pointer to a double?


May be not, because my conjecture says wen u declare a pointer of a type the num of bytes reqd for the type is allocted and remains const.

1 comment:

Prasanna said...

no p is stil a pointer to int because now the vale of i is the value of q without the precision that is rounded off the lower bound integer value.....narrower to wider happens only during operators and not during assignments