LOGBOOK

HELP

Quiz Entry - updated: 2026.07.10

How do you copy a struct in C?

Plain assignment (p2 = p1) copies every member — but it's a shallow copy, so any pointer member still points at the same shared data.

struct point { int x, y; };

struct point p1 = {10, 20};
// Copies all members!
struct point p2 = p1;

// p1.x is still 10 - they're independent
p2.x = 100;

Works for assignment and function return:

struct point make_point(int x, int y) {
    struct point p = {x, y};
    // Returns a copy
    return p;
}

struct point p = make_point(5, 10);

Warning - shallow copy for pointers:

struct person {
    // Pointer!
    char *name;
    int age;
};

struct person p1 = {"Alice", 30};
// Copies the POINTER, not the string!
struct person p2 = p1;

// Changes p1.name too! Both point to same string
p2.name[0] = 'X';

For deep copy, manually copy pointed-to data:

struct person deep_copy(struct person *src) {
    struct person dst;
    // Allocate and copy string
    dst.name = strdup(src->name);
    dst.age = src->age;
    return dst;
}

From Quiz: REVE1 / C Programming | Updated: Jul 10, 2026