Copying structure members

前端 未结 4 1192
既然无缘
既然无缘 2021-01-28 04:46

I am more confused with structures. There are many ways to copy a structure.

struct complex
{
   int real;
   int imaginary;
};

Assume c1 is complex structure v         


        
4条回答
  •  一向
    一向 (楼主)
    2021-01-28 05:17

    Of course the only sane way is to use assignment:

    c1 = *c2;
    

    It's true that the actual numerical value of c2, a pointer to a structure, is the same as the address of the first member. But that't doesn't matter. The types of the values involved in the assignment are both struct complex, that is what the assignment is working with and all needed bits will be copied.

    Do not use memcpy() to copy a structure, there is absolutely no point! It can in fact be a net negative, since th structure can contain padding which the assignment operator (being an operator, whose code generation is controlled by the compiler for this specific usage) can deal with and skip over, saving time. The function memcpy() has no idea of the padding of course, it's job is to copy all bytes and that's what it will do.

    Also, of course, do not use memcpy() to copy individual int-sized members. That's just ... not right, don't do that.

    Also, the assignment is higher-level, thus more abstract, and thus more compact and communicates more efficiently.

    Of course, if the structure contains pointers of its own (yours does not) you must take care to do a deep copy, and allocate new instances of the pointed-to data and copying that too. That has nothing to do with how the actual copying is done though.

    Use struct assignment. Always.

提交回复
热议问题