Is memcpy of a pointer the same as assignment?

前端 未结 9 1054
你的背包
你的背包 2020-12-03 16:23

Introduction: This question is part of my collection of C and C++ (and C/C++ common subset) questions regarding the cases where pointers object with strictly ide

9条回答
  •  时光说笑
    2020-12-03 17:11

    A pointer is simply an unsigned integer whose value is the address of some location in memory. Overwriting the contents of a pointer variable is no different than overwriting the contents of normal int variable.

    So yes, doing e.g. memcpy (&p, &pa1, sizeof p) is equivalent of the assignment p = pa1, but might be less efficient.


    Lets try it a bit differently instead:

    You have pa1 which points to some object (or rather, one beyond some object), then you have the pointer &pa1 which points to the variable pa1 (i.e. the where the variable pa1 is located in memory).

    Graphically it would look something like this:

    +------+     +-----+     +-------+
    | &pa1 | --> | pa1 | --> | &a[1] |
    +------+     +-----+     +-------+
    

    [Note: &a[0] + 1 is the same as &a[1]]

提交回复
热议问题