Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming. How to deep copy a struct?

I have the following two structs where "child struct" has a "rusage struct" as an element.

Then I create two structs of type "child" let's call them childA and childB

How do I copy just the rusage struct from childA to childB?

typedef struct{                         
        int numb;
        char *name;
        pid_t pid;
        long userT;
        long systemT;
        struct rusage usage;
}child;


typedef struct{
    struct timeval ru_utime; /* user time used */
    struct timeval ru_stime; /* system time used */
    long   ru_maxrss;        /* maximum resident set size */
    long   ru_ixrss;         /* integral shared memory size */
    long   ru_idrss;         /* integral unshared data size */
    long   ru_isrss;         /* integral unshared stack size */
    long   ru_minflt;        /* page reclaims */
    long   ru_majflt;        /* page faults */
    long   ru_nswap;         /* swaps */
    long   ru_inblock;       /* block input operations */
    long   ru_oublock;       /* block output operations */
    long   ru_msgsnd;        /* messages sent */
    long   ru_msgrcv;        /* messages received */
    long   ru_nsignals;      /* signals received */
    long   ru_nvcsw;         /* voluntary context switches */
    long   ru_nivcsw;        /* involuntary context switches */

}rusage;

I did the following, but I guess it copies the memory location, because if I changed the value of usage in childA, it also changes in childB.

memcpy(&childA,&childB, sizeof(rusage));

I know that gives childB all the values from childA. I have already taken care of the others fields in childB, I just need to be able to copy the rusage struct called usage that resides in the "child" struct.

like image 550
user69514 Avatar asked Sep 24 '09 23:09

user69514


People also ask

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.

Can you copy one structure into another in C?

If the structures are of compatible types, yes, you can, with something like: memcpy (dest_struct, source_struct, sizeof (*dest_struct)); The only thing you need to be aware of is that this is a shallow copy.

What is deep copy in C?

A deep copy, in contrast, means that you copy an entire object (struct). If it has members that can be copied shallow or deep, you also make a deep copy of them.

How do you copy an array to a struct?

1) Add a declaration structure * pStructure; to your code. 2) Add pStructure = (structure *) array; ` right after array's declaration. 3) Then, at the line where the memcpy is, set a breakpoint.


1 Answers

Simply:

childB.usage = childA.usage;
like image 63
nos Avatar answered Sep 19 '22 13:09

nos