copy struct to buffer

T

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.
 
H

heltena

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;
 
K

Krishanu Debnath

tom said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top