mercredi 6 juillet 2016

memcpy sturcture variables in C++

It might sound a very basic question but I have following structure in C++:

struct SMessage
{
    unsigned int id; 
    unsigned int payloadSize; 
    unsigned char data[100];  
    unsigned char *data2; 
}; 

lets say I have two variables of SMessage type (msg1,msg2) and i want to memcpy individual members of msg1 into msg2 (please dont ask why!). I understand that copying id and payLoadSize are relatively straight forward:

memcpy(&msg2.id, &msg1.id, sizeof(unsigned int)); 
memcpy(&msg2.payLoadSize, &msg2.payLoadSize, sizeof(unsigned int));

but for copying the data[] should we do:

memcpy(&msg2.data, &msg1.data, 100*sizeof(unsigned char)); 

or

memcpy(msg2.data, msg2.data, 100*sizeof(unsigned int)) 

would also work because data is an array object?

How will we copy the struct member data2 which is declared as a pointer instead?

Aucun commentaire:

Enregistrer un commentaire