Copying structure in C with assignment instead of memcpy()

后端 未结 5 1022
孤街浪徒
孤街浪徒 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:38

    I'm resurrecting this old question because the answers do not explain why memcpy is actually preferred.

    memcpy is preferred because it makes it clear the programmer wants to copy the content and not simply the pointers.

    In the following example, the two assignments make two very different things:

    struct Type *s1,*s2;
    *s1=*s2;
    s1=s2;
    

    Inadvertently using one instead of the other may have disastrous effects. The compiler won't complain. Unless the program crashes when an uninitialized pointer is used, the error can go unnoticed for a long time and produce strange side effects.

    Writing it as one of:

    memcpy(s1,s2,sizeof(*s1));
    memcpy(s1,s2,sizeof(*s2));
    memcpy(s1,s2,sizeof(struct Type));
    

    let the reader knows that the intent is to copy the content (at the expense of type safety and bounds checking).

    Some compilers (gcc for instance) even issue a warning about the sizeof when they encounter something like:

    memcpy(s1,s2,sizeof(s1));
    

提交回复
热议问题