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