Copying structure members

前端 未结 4 1301
既然无缘
既然无缘 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:27

    I you change the order of fields in the following way:

    struct complex
    {
        int imaginary;
        int real;
    );
    

    Then memcpy(&c1.real, &c2->real, sizeof(struct complex)) will try to copy fields starting from real and as the number of bytes you are trying to copy is the size of the whole structure it will access memory after the structure thus causing invalid memory access in some cases and in some cases it will does not produce any error. But the result of this operation is not what you expected. For ones, it will not copy the field imaginary.

    In case of you need to copy part of the structure - this is the way to do it:

    memcpy(&c1.real, &c2->real, sizeof(struct complex) - offsetof(struct complex, real));
    

    Where offsetof is a macro declared like here.

提交回复
热议问题