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); }
In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable.
memcpy (dest_struct, source_struct, sizeof (*dest_struct)); dest_struct->strptr = strdup (source_struct->strptr); This will copy the entire contents of the structure, then deep-copy the string, effectively giving a separate string to each structure.
Yes, you can assign one instance of a struct to another using a simple assignment statement. In the case of non-pointer or non pointer containing struct members, assignment means copy. In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.
To perform a deep copy you must first free any memory that was being pointed to by the destination structure. Then allocate enough memory to hold the strings pointed to by the source structure. Now, strncpy the strings over.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With