What are the rules for casting pointers in C?

前端 未结 5 622
梦毁少年i
梦毁少年i 2020-12-04 04:35

K&R doesn\'t go over it, but they use it. I tried seeing how it\'d work by writing an example program, but it didn\'t go so well:

#include 

        
5条回答
  •  再見小時候
    2020-12-04 05:28

    I suspect you need a more general answer:

    There are no rules on casting pointers in C! The language lets you cast any pointer to any other pointer without comment.

    But the thing is: There is no data conversion or whatever done! Its solely your own responsibilty that the system does not misinterpret the data after the cast - which would generally be the case, leading to runtime error.

    So when casting its totally up to you to take care that if data is used from a casted pointer the data is compatible!

    C is optimized for performance, so it lacks runtime reflexivity of pointers/references. But that has a price - you as a programmer have to take better care of what you are doing. You have to know on your self if what you want to do is "legal"

提交回复
热议问题