将 char 数组转换为 struct * 类型

标签 c arrays pointers struct casting

在下面的代码中,有人可以解释 struct ether_header *eh = (struct ether_header *) sendbuf; 线上发生了什么吗? ?我知道它正在创建一个指针 eh类型 ether_header在 RHS 上您正在转换 sendbuf成为tyoe的指针struct ether_header 。但你怎么能做到这一点是sendbufchar array ?还有你为什么要这样做?

这里是完整代码的链接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;

最佳答案

But how can you do this isif sendbuf is a char array?

代码不应该这样做。

将指针强制转换为最初不是该类型的有效指针的类型是未定义行为 (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;
<小时/>

Also why would you do this?

允许从 2 个数据类型角度访问数据。也许是为了对 u 进行数据转储。

关于将 char 数组转换为 struct * 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099028/

相关文章:

c++ - 怎么realloc不行,malloc可以呢?

C 指针使用数组和变量接受值之间的区别?

c# - 判断对象是否为任意类型的数组,并获取数组长度

C++ 引用和指针

C的怪异指针运算2

c - 如何使用 MPI C 文件中的索引修改字符串?

c - C 中字符串管理的指针 : Replacing specific characters in a string

c - 跟踪 C 中的函数调用

ios - 错误: value of type 'Optional<NSMutableArray>' has no subscripts Array[0] in Swift iOS

c - 给array seat赋值很慢