Pointer/address type casting

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

    The correct way to do this would be:

    int I = 65;
    char* p = (char*)&I;
    

    &I gives you an int* that points to I; you then cast this to a char* and assign it to p.

    Note that you shouldn't ordinarily cast between pointers of unrelated types. A char* can be used to access any object, though, so in this particular case it is safe.

提交回复
热议问题