I have the following variables:
char *p;
int l=65;
Why do the following casts fail?
(int *)p=&l;
and:
The result of type conversion is always an rvalue. Rvalue cannot be assigned to, which is why your first expression doesn't compile. Rvalue cannot be taken address of, which is why your second expression doesn't compile.
In order to perform the correct type conversion, you have to to it as follows
p = (char *) &l;
This is the proper way to do what you tried to do in your second expression. It converts int *
pointer to char *
type.
Your first expression is beyond repair. You can do
*(int **) &p = &l;
but what it does in the end is not really a conversion, but rather reinterpretation of the memory occupied by char *
pointer as int *
pointer. It is an ugly illegal hack that most of the time has very little practical value.