Copy struct to struct in C
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.
Your code is correct. You can also assign one directly to the other (see Joachim Pileborg's answer).
When you later come to compare the two structs, you need to be careful to compare the structs the long way, one member at a time, instead of using memcmp
; see How do you compare structs for equality in C?
copy structure in c you just need to assign the values as follow:
struct RTCclk RTCclk1;
struct RTCclk RTCclkBuffert;
RTCclk1.second=3;
RTCclk1.minute=4;
RTCclk1.hour=5;
RTCclkBuffert=RTCclk1;
now RTCclkBuffert.hour will have value 5,
RTCclkBuffert.minute will have value 4
RTCclkBuffert.second will have value 3