Why is arr and &arr the same?

前端 未结 6 748
鱼传尺愫
鱼传尺愫 2020-12-07 21:12

I have been programming c/c++ for many years, but todays accidental discovery made me somewhat curious... Why does both outputs produce the same result in the code below? (<

6条回答
  •  余生分开走
    2020-12-07 21:40

    #include 
    
    struct foo {
        int x;
        int y;
    };
    
    int main() {    
        foo f;
        void* a = &f.x;
        void* b = &f;
        assert(a == b);
    }
    

    For the same reason the two addresses a and b above are the same. The address of an object is the same as the address of its first member (Their types however, are different).

                                arr
                          _______^_______
                         /               \
                        | [0]   [1]   [2] |
    --------------------+-----+-----+-----+--------------------------
          some memory   |     |     |     |        more memory
    --------------------+-----+-----+-----+--------------------------
                        ^
                        |
               the pointers point here
    

    As you can see in this diagram, the first element of the array is at the same address as the array itself.

提交回复
热议问题