Jump to content

Struct with char* to char array?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
manux

manux

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 234 posts
Hey all,

I have this struct:


struct Msg

{

   unsigned char header;

   unsigned short length;

   char* data;

};

What I want, is to pass this struct through a socket, that is, to convert it into a char array.
I guess something like this will not work:
...makeMsg(MessageHeader id,char* data,int datasize)

{

    Msg msg;

    msg.header=(unsigned char)id;

    msg.length=datasize;

    msg.data=data;


    char* msgstr = new char[sizeof(Msg)];

    memcpy(msgstr,&msg,sizeof(Msg));

...

}
It won't copy the data I guess... since it's of a variable width.
How can I make it work?

#2
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,714 posts
This requires some fun pointer arithmetic.

char *messageToByteArray(const Msg& msg, size_t& array_size)
{
	char *pdata = new char[msg.length + sizeof(short) + sizeof(char)];
	*pdata = msg.header;
	*((short *)(pdata + 1)) = msg.length;
	memcpy(pdata + sizeof(char) + sizeof(short),msg.data,msg.length);
	array_size = msg.length + sizeof(short) + sizeof(char);
	return pdata;
}

Edited by dargueta, 17 March 2009 - 10:22 PM.
Forgot something