将char数组强制转换为struct *类型 [英] Casting a char array to be of type struct *
问题描述
在下面的代码中,也许有人可以解释struct ether_header *eh = (struct ether_header *) sendbuf;
行上发生了什么?我了解它正在创建类型为ether_header
的指针eh
,并且在RHS上,您正在将sendbuf
强制转换为tyoe struct ether_header
的指针.但是,如果sendbuf
是char array
,该怎么办?还有你为什么要这样做呢?
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 is creating a pointer eh
of type ether_header
and on the RHS you are casting sendbuf
to be a pointer of tyoe struct ether_header
. But how can you do this is sendbuf
is a char array
? Also why would you do this?
此处是完整代码的链接发送以太网帧
Here is the link to the full code send ethernet frame
#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
数组,那么如何执行is?
But how can you do this
isifsendbuf
is achar
array?
代码不应该这样做.
将指针投射到最初不是该类型的有效指针的类型是未定义行为(UB).
Casting a pointer to a type that was not originally a valid pointer for that type is undefined behavior (UB).
char sendbuf[BUF_SIZ];
struct ether_header *eh = (struct ether_header *) sendbuf; // UB
至少要考虑struct ether_header
是否具有对齐要求,以使其为偶数地址,而sendbuf[]
是否以奇数地址开始.作业可能会终止程序.
At a minimum, consider if struct ether_header
had an alignment requirement to be an even address and sendbuf[]
began on an odd address. The assignment may kill the program.
第二个问题是未发布的代码以后可能会使用sendbuf[]
和eh
做什么,这会违反严格的别名规则
A 2nd concern is what unposted code might later do with sendbuf[]
and eh
which can violating strict aliasing rule @Andrew Henle.
更好的方法是使用union
.现在,成员已对齐,并且union
处理严格的别名规则.
A better approach is to use a union
. Now the members are aligned and the union
handles the strict aliasing rule.
union {
char sendbuf[BUF_SIZ];
struct ether_header eh;
} u;
您为什么还要这么做?
Also why would you do this?
允许从2个数据类型的角度访问数据.也许要进行u
的数据转储.
To allow access to the data from 2 data type perspectives. Perhaps to make a data dump of u
.
这篇关于将char数组强制转换为struct *类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!