Pointer/address type casting

后端 未结 5 1697
梦如初夏
梦如初夏 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:17

    (int *)p=&l;

    The line above doesn't work, because as soon as you cast p to (int*), the result is an anonymous temporary object, which is an rvalue and not an lvalue; consquently, the result cannot receive the assignment, and even if the language did allow it, you'd be assigning to a temporary casted copy of p, not to the original p.

    p=&((char) l);

    The line above does not work for a similar reason; the result of (char) l is a temporary object that is a copy of l casted to the type char. Consequently, because it is temporary, you cannot take its address.

    Insead, you can use:

    p = (char*) &l
    

提交回复
热议问题