Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copy One Struct Member to Another Struct

I’m struggling with this syntax: I have a few structs of arrays:

struct Msg {
    uint8_t Data[DATA_SIZE];
};

struct Msg Msg_Buff[NUM_MESSAGES], Temp_Buff[NUM_MESSAGES];

and want to copy one array from one struct to another.

This:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

*Temp_Buff[Other_Indx].Data = *Msg_Buff[This_Indx].Data;

copies ONLY the first element of the array, not the whole array. What am I doing wrong?

>Solution :

You need to use memcpy for that if you want to copy only one member.

#define DATA_SIZE 100
#define NUM_MESSAGES 200

struct Msg {
    uint8_t Data[DATA_SIZE];
};

struct Msg Msg_Buff[NUM_MESSAGES], Temp_Buff[NUM_MESSAGES];


void copyDataAtIndex(size_t index)
{
    memcpy(Temp_Buff[index].Data, Msg_Buff[index].Data, sizeof(Temp_Buff[index].Data));
}

If you want to copy the whole struct – simply assign:

void copyStructAtIndex(size_t index)
{
    Temp_Buff[index] = Msg_Buff[index];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading