Click here to Skip to main content
15,896,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
Posted

1 solution

Properly used, memcpy must work. e.g.

C++
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:
C++
buf = { 05 00 00 00 FF FF FF FF 41 00 00 00 }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900