Search code examples
carrayspointersstructdynamic-memory-allocation

Is the C `=` operator copying memory when applied between structs?


Consider this example:

typedef struct {
    int x;
    int y;
    ...
} ReallyBigItem;

ReallyBigItem* array = (ReallyBigItem*) malloc(sizeof(ReallyBigItem) * 8);

ReallyBigItem* item = (ReallyBigItem*) malloc(sizeof(ReallyBigItem));
item->x = 0;
item->y = 1;

array[0] = *item;

ReallyBigItem* array = (ReallyBigItem*) malloc(sizeof(ReallyBigItem) * 8);

I am allocating space for an array that fits in 8 ReallyBigItem structs.

ReallyBigItem* item = (ReallyBigItem*) malloc(sizeof(ReallyBigItem));

I am allocating space for a ReallyBigItem and storing it's memory address in item.

array[0] = *item;

Now I am setting the first element of the array to that item.

My question is:

Is the = operator actually copying over the already allocated memory? So the item struct exists in memory twice?


Solution

  • So the item struct exists in memory twice?

    The content of the struct that item points to exists twice after the assignment in question, yes.

    Explanation:

    Both operands of this expression

    array[0] = *item;
    

    evaluate to a struct.

    The = is defined for struts.

    So the above expression copies data (memory's content, not "memory" as you word) from the right struct to the left.

    This might be more obvious if you take into account that *item actually is the same as item[0], so the above expression is equivalent to:

    array[0] = item[0];