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 another generally looks like
struct block *b0 = malloc(sizeof(struct block));
struct block *b1 = malloc(sizeof(struct block));
/* populate fields in *b0 */
memcpy(b1, b0, sizeof *b1); /* copy contents of b0 into b1 */
/* free b0, b1 */
However, this task can also be accomplished by a simple assignment replacing the memcpy()
.
*b1 = *b0; /* dereferenced struct assignment */
Is there good reason why this isn't as widely used (at least in my limited experience)? Are these two methods—assignment and memcpy()
—equivalent, or is there some compelling reason to use memcpy()
in general?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…