Копирование объекта

Классы

//the name lives in the heap: the struct holds only a pointer to it
typedef struct {
    char *name;
    int lineCount;
} Shape;

//assignment copies the fields, and a pointer is copied as an address
Shape shapeCopy(const Shape *source) {
    Shape copy = *source;
    //the deep copy makes its own text for the pointer field
    copy.name = strdup(source->name);
    return copy;
}

Shape square = {strdup("Square"), 4};

Shape shallow = square;
shallow.lineCount = 5;
//square.lineCount is 4: a plain field is copied

shallow.name[0] = 's';
//square.name is "square": the text is shared
bool shared = shallow.name == square.name;
//shared is true

Shape deep = shapeCopy(&square);
deep.name[0] = 'X';
//square.name is "square", deep.name is "Xquare"

printf("square.lineCount is %d\n", square.lineCount);
printf("square.name is %s\n", square.name);
printf("shared is %s\n", shared ? "true" : "false");
printf("deep.name is %s\n", deep.name);

//shallow and square own one text: it is freed once
free(square.name);
free(deep.name);