cstructcopymicrochip

Copy struct to struct in C


I want to copy an identical struct into another and later on use it as a comparance to the first one. The thing is that my compiler gives me a warning when Im doing like this! Should I do it in another way or am I doing this wrong:

In header File:

extern struct RTCclk
{
uint8_t second;
uint8_t minute;
uint8_t hour;
uint8_t mday;
uint8_t month;
uint8_t year;
}
RTCclk;

In C file:

struct RTCclk RTCclk;
struct RTCclk RTCclkBuffert;

void FunctionDO(void)
{
   ... // Some Code
   /* Copy first struct values into the second one */
   memcpy(&RTCclk, &RTCclkBuffert, sizeof RTCclk);
}

Solution

  • For simple structures you can either use memcpy like you do, or just assign from one to the other:

    RTCclk = RTCclkBuffert;
    

    The compiler will create code to copy the structure for you.


    An important note about the copying: It's a shallow copy, just like with memcpy. That means if you have e.g. a structure containing pointers, it's only the actual pointers that will be copied and not what they point to, so after the copy you will have two pointers pointing to the same memory.