[問題] 兩結構近似的struct互相轉型

作者: kkroy (☆㊣↖煞氣ㄟ阿喂↘ξ★)   2018-05-18 01:38:24
問題是這樣的,我知道 TCP 與 UDP 的表頭前四個 byte 是一樣的
分別代表
source port: 2 byte
以及
destination port : 2 byte
假設現在我能從 socket buffer 取得它的表頭,但是我只能取成 TCP 型別的表頭
或 UDP 型別的表頭。
那只取前 4 byte 的話,是不是不論何種型別(TCP、UDP)都沒差別呢?
簡單的實驗如下:
#include <stdio.h>
typedef struct A{
int x;
int y;
float f;
}A_s;
typedef struct B{
int x;
int y;
double d;
struct AA{
int i;
int j;
};
int z[3];
}B_s;
int main(void){
// define A
A_s objA;
objA.x=1;
objA.y=2;
// define B
B_s objB;
objB.x=100;
objB.y=200;
objB.z[0]=300;
objB.z[1]=301;
objB.z[2]=302;
A_s* ptrA;
B_s* ptrB;
ptrA = (A_s*)&objB;
//another type casting
ptrB = (B_s*)&objA;
printf("x = %d, y = %d \n", ptrA->x, ptrA->y); // print x = 100, y = 200
printf("x = %d, y = %d \n", ptrB->x, ptrB->y); // Print x = 1, y = 2
return 0;
}
由以上實驗顯示, 大的 struct 轉型成小的 struct , 存取變數 x, y 正常
小的 struct 轉型成大的 struct ,存取變數 x, y 也正常
這樣的用法是不是如果不踩出去未知的記憶體空間,就沒問題呢?
謝謝大家!
作者: bluesoul (忙死你老爸)   2018-05-18 01:47:00
如果layout相同,可以
作者: chuegou (chuegou)   2018-05-18 08:57:00
同樓上 注意是否因為記憶體對齊可能造成的問題
作者: Qbsuran (Qbsuran)   2018-05-18 12:45:00
可以 記得把struct對齊關掉 或是用union
作者: andyjy12 (??)   2018-05-21 08:02:00
Big little 有差嗎?

Links booklink

Contact Us: admin [ a t ] ucptt.com