将Structure的数据复制到缓冲区中. [英] Copying data of Structure into a buffer.

查看:55
本文介绍了将Structure的数据复制到缓冲区中.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想将结构的数据复制到缓冲区中.我使用了memcpy()函数,但由于结构存在填充问题而无法使用.我的结构变量为unsigned char,intn和char类型.

有人可以建议我如何将结构数据复制到缓冲区中吗?


感谢

解决方案

正确使用memcpy必须正常工作.例如

 结构 MyStruct
{
  未签名 字符 u;
   int  i;
  字符 c;
};

#include   ><  > 
 #include   <  字符串 > 


 int  main()
{
   unsigned   char  buf [0x100];

  MyStruct m;
  m.u =  5 ;
  m.i =- 1 ;
  m.c = '  A';

  memcpy(buf,& m, sizeof (m));


  printf(" ));
   for ( size_t  i; i< sizeof(m); i ++)
  {
    printf(" ,buf [i]);
  }
  printf(" );

} 



输出:

 buf = { 05   00   00   00  FF FF FF FF  41   00   00   00 } 


Hi
I want to copy the data of structure into a buffer.I used memcpy() function but it doesn''t work, as structure has padding problem.Variables of my structure is of unsigned char,intn and char type.

Can anybody suggest me how to copy structure data into a buffer.


thanks

解决方案

Properly used, memcpy must work. e.g.

struct MyStruct
{
  unsigned char u;
  int i;
  char c;
};

#include <cstdio>
#include <cstring>


int main()
{
  unsigned char buf[0x100];

  MyStruct m;
  m.u = 5;
  m.i =  -1;
  m.c = 'A';

  memcpy(buf, &m, sizeof(m));


  printf("buf = { ");
  for (size_t i; i<sizeof(m); i++)  
  {
    printf("%02X ", buf[i]);
  }
  printf("}\n");

}



outputs:

buf = { 05 00 00 00 FF FF FF FF 41 00 00 00 }


这篇关于将Structure的数据复制到缓冲区中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆