[英]Casting a char array to be of type struct *
在下面的代码中,也许有人可以解释一下这行上发生的事情: struct ether_header *eh = (struct ether_header *) sendbuf;
? 我知道它正在创建类型为ether_header
的指针eh
,并且在RHS上,您将sendbuf
强制sendbuf
为tyoe struct ether_header
的指针。 但是,如何处理sendbuf
是一个char array
呢? 还有你为什么要这样做?
这是完整代码发送以太网帧的链接
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/ether.h>
int main(int argc, char *argv[])
{
int sockfd;
struct ifreq if_idx;
struct ifreq if_mac;
int tx_len = 0;
char sendbuf[BUF_SIZ];
struct ether_header *eh = (struct ether_header *) sendbuf;
但是,你怎么能做到这
一点,如果sendbuf
是一个char
数组?
代码不应该这样做。
将指针强制转换为最初不是该类型的有效指针的类型是未定义行为 (UB)。
char sendbuf[BUF_SIZ];
struct ether_header *eh = (struct ether_header *) sendbuf; // UB
至少要考虑struct ether_header
是否具有对齐要求,以使其为偶数地址,并且sendbuf[]
从奇数地址开始。 作业可能会终止程序。
第二个问题是未发布的代码以后可能会对sendbuf[]
和eh
,这可能违反严格的别名规则@Andrew Henle 。
更好的方法是使用union
。 现在,成员已对齐,并且union
处理严格的别名规则。
union {
char sendbuf[BUF_SIZ];
struct ether_header eh;
} u;
还有你为什么要这样做?
允许从2个数据类型的角度访问数据。 也许要转储u
的数据。
char sendbuf[BUF_SIZ]
分配了一个char sendbuf[BUF_SIZ]
块(即,在大多数系统上为字节),并且struct ether_header *eh = (struct ether_header *) sendbuf
表示您明确希望将其视为struct ether_header
类型。 除了(可能)设置CPU寄存器之外,此强制转换没有重要的说明。
您最终将获得两个指向同一内存块的指针。 修改其中一个会影响另一个。
话虽如此,它并不完全正确/安全,因为sendbuf
可能未适当对齐以实际包含struct ether_header
。
编辑:关于结构别名规则,明确允许使用char*
作为任何其他数据类型的别名,但反之并不一定成立。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.