Pointer/address type casting

后端 未结 5 1703
梦如初夏
梦如初夏 2021-02-02 14:50

I have the following variables:

char *p;
int l=65;

Why do the following casts fail?

(int *)p=&l;

and:

5条回答
  •  渐次进展
    2021-02-02 15:18

    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.

提交回复
热议问题