Copying structure in C with assignment instead of memcpy()

后端 未结 5 1128
孤街浪徒
孤街浪徒 2020-12-08 15:07

Up until recently, I have only seen copying of structure fields done with memcpy(). In classes and online instructions, copying the contents of one struct into

5条回答
  •  天命终不由人
    2020-12-08 15:53

    Some people prefer memcpy because that's what they learned and they never figured out that they could just do an assignment (in ancient times the assignment wasn't allowed, but that's a long long time ago). There are no alignment problems to worry about since memory allocated by malloc () is always aligned correctly. And since a compiler could trivially translate this assignment to a memcpy call, it would never be slower or more code than memcpy. Of course there are embedded systems with badly outdated compilers.

提交回复
热议问题