C Programming. How to deep copy a struct?

user69514 picture user69514 · Sep 25, 2009 · Viewed 33.8k times · Source

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.

Answer

nos picture nos · Sep 25, 2009

Simply:

childB.usage = childA.usage;