作者kkroy (☆㊣↖煞气ㄟ阿喂↘ξ★)
看板C_and_CPP
标题[问题] 两结构近似的struct互相转型
时间Fri May 18 01:38:24 2018
问题是这样的,我知道 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 也正常
这样的用法是不是如果不踩出去未知的记忆体空间,就没问题呢?
谢谢大家!
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 123.192.15.168
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1526578706.A.6ED.html
※ 编辑: kkroy (123.192.15.168), 05/18/2018 01:41:37
1F:→ bluesoul: 如果layout相同,可以 05/18 01:47
2F:推 chuegou: 同楼上 注意是否因为记忆体对齐可能造成的问题 05/18 08:57
3F:推 Qbsuran: 可以 记得把struct对齐关掉 或是用union 05/18 12:45
4F:推 andyjy12: Big little 有差吗? 05/21 08:02