cstructdeep-copy

Deep copying structs with char arrays in C (How to copy the arrays?)


I have the following struct in my C program

struct person {
    char key[50];
    char color[20];
    int age;
};

I want to make a deep copy of this struct. I've got my deep copy function setup however I'm a bit confused about how to deep copy strings. I've heard of people using strcpy and others using strdup.

What I want in my program is for the deep copied person's key and color not to be affected if the original person is freed. Once set, the key and color cannot change. For my purpose, should I be using the strcpy or strdup function?


Solution

  • There is a difference between strcpy() and strdup().

    It seems that in your case it's strcpy() because the fields of your structure are not pointers so you can't assign to them a pointer to allocated space which is what strdup() returns.

    However, as explained in this answer you actually don't need to.