繁体   English   中英

两个C片段之间的差异

[英]Difference between two C snippets

我很茫然地解释了为什么这两个C代码片段的行为方式不同。 我正在尝试将两个结构eh和ah序列化为单个字节缓冲区(uint8_t)。 第一个代码块有效,第二个代码块无效。 我不知道有什么区别。 如果有人可以向我解释,将不胜感激。

区块1:

uint8_t arp_reply_buf[sizeof(eh) + sizeof(ah)];
uint8_t *eh_ptr = (uint8_t*)&eh;
for (int i = 0; i < sizeof(eh); i++)
{
    arp_reply_buf[i] = eh_ptr[i];
}
uint8_t *ah_ptr = (uint8_t*)&ah;
int index = 0;
for (int i = sizeof(eh); i < (sizeof(eh) + sizeof(ah)); i++)
{
    arp_reply_buf[i] = ah_ptr[index++];
}

区块2:

uint8_t arp_reply_buf[sizeof(eh) + sizeof(ah)];
arp_reply_buf[0] = *(uint8_t *)&eh;
arp_reply_buf[sizeof(eh)] = *(uint8_t *)&ah;

在第二个示例中,您仅在两个索引中设置值:

  1. arp_reply_buf[0]

     arp_reply_buf[0] = *(uint8_t *)&eh; 
  2. arp_reply_buf[sizeof(eh)]

     arp_reply_buf[sizeof(eh)] = *(uint8_t *)&ah; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM