Is it possible to cast struct to another?

后端 未结 4 536
名媛妹妹
名媛妹妹 2020-12-28 19:03

Any one could describe how (struct sockaddr *)&server works here? Is it possible to cast bigger struct to smaller struct?

See these structs:

相关标签:
4条回答
  • 2020-12-28 19:36

    This is C's form of "inheritance" (notice the quotes). This works because C does not care about the underlying data in an address, just what you represent it as.

    The function determines what structure it actually is by using the sa_family field, and casting it into the proper sockaddr_in inside the function.

    0 讨论(0)
  • 2020-12-28 19:41

    In C, it's possible to cast anything to anything. You could even omit the cast to (struct sockaddr*), and probably just get a compiler warning.

    0 讨论(0)
  • 2020-12-28 19:49

    You can cast sockaddr_in to sockaddr, but you cannot usually cast ANY struct to ANY other and assume that things will work properly.

    0 讨论(0)
  • 2020-12-28 19:56

    This is refered as Type Punning. Here, both structures have the same size, so there is no question of struct size. Although you can cast almost anything to anything, doing it with structures is error-prone.

    0 讨论(0)
提交回复
热议问题