//имя лежит в куче: структура хранит только указатель на него
typedef struct {
char *name;
int lineCount;
} Shape;
//присваивание копирует поля, а указатель копируется как адрес
Shape shapeCopy(const Shape *source) {
Shape copy = *source;
//полная копия создаёт собственный текст для поля-указателя
copy.name = strdup(source->name);
return copy;
}
Shape square = {strdup("Square"), 4};
Shape shallow = square;
shallow.lineCount = 5;
//square.lineCount равно 4: обычное поле копируется
shallow.name[0] = 's';
//square.name равно "square": текст общий
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 и square владеют одним текстом: он освобождается один раз
free(square.name);
free(deep.name);