Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); } 
like image 359
Christian Avatar asked Feb 03 '12 10:02

Christian


People also ask

Can we copy struct in C?

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.

How do you copy a structure to another structure?

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.

Can you assign a struct to another struct in C?

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.

How do you deep copy a struct?

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.


1 Answers

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.

like image 197
2 revs Avatar answered Sep 30 '22 11:09

2 revs