簡體   English   中英

將char數組強制轉換為struct *類型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM