Casting a char array to be of type struct *

后端 未结 2 976
日久生厌
日久生厌 2021-01-13 13:55

In the code below could somebody perhaps explain what is happening on the line struct ether_header *eh = (struct ether_header *) sendbuf;? I understand that it

2条回答
  •  难免孤独
    2021-01-13 14:46

    The line char sendbuf[BUF_SIZ] allocates a block of chars (i.e. bytes on most systems) and the cast struct ether_header *eh = (struct ether_header *) sendbuf says that you explicitly want to treat this as a struct ether_header type. There are no significant instructions from this cast, aside from (possibly) setting a CPU register.

    You'll end up with two pointers to the same block of memory. Modification of one will affect the other.

    That being said, it is not completely correct/safe, because the sendbuf may not be appropriately aligned to actually contain a struct ether_header.

    Edit: In regard to struct aliasing rules a char* is explicitly allowed to alias any other data type, but the reverse is not necessarily true.

提交回复
热议问题