I have this code to transfer the contents of my struct into a char array:
Code:
#include <stdio.h>
#include <string.h>
struct msg_on_send
{
char descriptor_msg[5];
int address;
char space;
char cmdmsg[5];
char CR;
char LF;
};
size_t serialize(unsigned char *dst, const struct msg_on_send *object)
{
size_t i = 0;
memcpy(&dst[i], &object->descriptor_msg, sizeof object->descriptor_msg);
i += sizeof object->descriptor_msg;
memcpy(&dst[i], &object->address, sizeof object->address);
i += sizeof object->address;
memcpy(&dst[i], &object->space, sizeof object->space);
i += sizeof object->space;
memcpy(&dst[i], &object->cmdmsg, sizeof object->cmdmsg);
i += sizeof object->cmdmsg;
return i;
}
void showbytes(const void *object, size_t size)
{
const unsigned char *byte;
for ( byte = object; size--; ++byte )
{
printf("%02X", *byte);
}
putchar('\n');
}
int main()
{
int member;
struct msg_on_send SendMsg_on[sizeof member] =
{
SendMsg_on.descriptor_msg = "$str_";
SendMsg_on.address = 0x02;
SendMsg_on.space = 0x20;
SendMsg_on.cmdmsg = "op_en";
SendMsg_on.CR = 0x0D;
SendMsg_on.LF = 0x0A;
};
unsigned char buffer [ sizeof SendMsg_on[0] ];
showbytes(buffer, serialize(buffer, by));
system("PAUSE");
return 0;
}
In the original code this took a fixed array, is my modification of loading the struct members within main valid, if not, can you suggest what I could do instead?
--dave