When are pad bytes copied - struct assignment, pass by value, other?

后端 未结 3 471
小蘑菇
小蘑菇 2021-01-03 02:55

While debugging a problem, the following issue came up. (Please ignore minor code errors; the code is just for illustration.)

The following struct is defined:

<
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 03:13

    As Christoph said, there are no guarantees regarding the padding. Your best bet is to not use memcmp to compare two structs. It works at the wrong abstraction level. memcmp works byte-wise at the representation, while you need to compare the values of the members.

    Better use a separate compare function that takes two structs and compares each member separately. Something like this:

    int box_isequal (box_t bm, box_t bn)
    {
        return (bm.x == bn.x) && (bm.y == bn.y);
    }
    

    For your bonus, the three objects are separate objects, they are not part of the same array and pointer arithmetic between them is not allowed. As function local variables, they are usually allocated on the stack, and because they are separate the compiler can align them in any way that is best, e.g. for performance.

提交回复
热议问题