By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,462 Members | 799 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,462 IT Pros & Developers. It's quick & easy.

copy struct to buffer

P: n/a
tom
how to copy struct to buffer?

char * buffer;
buffer=(char *)malloc(5*20);
Data_O tt;
strcpy(tt.Name1, "John ");
strcpy(tt.Name2, "Brown ");
memcpy(buffer + 0,(const void*)tt, sizeof (tt)); // dasn't work
strcpy(tt.Name1, "Tom ");
strcpy(tt.Name2, "Backer ");
memcpy(buffer + 5,(const void*)tt, sizeof (tt)); // dasn't work
....

struct Data_O
{
char Name1[10+1];
char Name2[10+1];
};
t.
Sep 20 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
tom wrote:
how to copy struct to buffer?

char * buffer;
buffer=(char *)malloc(5*20);
Data_O tt;
strcpy(tt.Name1, "John ");
strcpy(tt.Name2, "Brown ");
Try this:

memcpy(buffer, &tt, sizeof tt);
memcpy(buffer + 0,(const void*)tt, sizeof (tt)); // dasn't work
strcpy(tt.Name1, "Tom ");
strcpy(tt.Name2, "Backer ");
memcpy(buffer + 5,(const void*)tt, sizeof (tt)); // dasn't work
memcpy(buffer + sizeof tt, &tt, sizeof tt);

Krishanu
Sep 20 '06 #2

P: n/a
char * buffer;
buffer=(char *)malloc(5*20);
Data_O tt;
strcpy(tt.Name1, "John ");
strcpy(tt.Name2, "Brown ");
memcpy(buffer + 0,(const void*)tt, sizeof (tt)); // dasn't work
tt is not a pointer, you must be use &tt.
strcpy(tt.Name1, "Tom ");
strcpy(tt.Name2, "Backer ");
memcpy(buffer + 5,(const void*)tt, sizeof (tt)); // dasn't work
Why not buffer + sizeof(tt) ?

Or:

char* buffer = new char[5 * sizeof(Data_O) ];
Data_O* tt = (Data_O*) buffer;
strcpy(tt->Name1, "John..");
strcpy(tt->Name2, "Brown");
tt = (Data_O*) (buffer + sizeof(Data_O));
strcpy(tt->Name1, "Tom");
strcpy(tt->Name2, "Backer");
....
delete[] buffer;

Sep 20 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.