Copying structure members

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

    Changing the order of structure members has no effect in this case. Struct fields are explicitly stated, as you mentioned.

    When things get more complex, it's easier to make mistakes. As you did:

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

    It should have been:

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

    Simpler is better:

    c1.real = c2->real;
    

    By using memcpy there is also another problem; you lose type safety. Sometimes you want that, but not usually when working with 2 entities with same data type.

提交回复
热议问题