数组基地址指针

时间:2017-06-05 10:45:22

标签: c++ arrays

鉴于以下代码,ptr和ptr2之间有什么区别?因为v的大小是20而而& v [0]的大小是4.为什么这甚至有效?为什么不像ptr * =& v这样的第三个指针。所有这些都有相同的基地址,但首先有什么区别......我很困惑。使用2d阵列时情况会变得更糟。谢谢你的帮助!

#include <iostream>
using namespace std;

int main(void)
{
    int v[5] = { 1, 2, 3, 4, 5 };
    int *ptr = v;
    int *ptr2 = &v[0];

    cout << sizeof(v) << endl << sizeof(&v[0]) << endl;
    cout << v << endl << &v << endl << &v[0];
    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:1)

int *ptr = v;的上下文中,数组v 衰减&v[0]。在sizeof(v)的上下文中,它仍然是一个数组。

答案 1 :(得分:0)

#include <stdio.h>
int main()
{
    printf("%zu\n", sizeof(int));
    // 4 (on a 64 bit arch)
    printf("%zu\n", sizeof(int*));
    // 8 (on a 64 bit arch)

    int v[5] = {0};

    /*Arrays are real and sizeof digs that.
      sizeof v == sizeof(int) * 5 
      */
    printf("%zu\n", sizeof v);
    // 20

    /*But,
      they convert to pointers to the first element 
      in pointer arithmetic expressions and in function calls
    */

    assert( v+0 == &v[0] );

    /*
       &v[0] != &v 

       While they're the same numerically:

    */
    assert ( (void*)&v == (void*)&v[0] );
#if 0
    /*They have distinct types and so this doesn't compile*/

    assert ( &v == &v[0] );
#endif

    /*The difference shows in pointer arithmetic*/

    /*adding 1 to v (== &v[0]) increments the pointer by sizeof(int) (== sizeof(v[0]) ) */
    assert ( (void*) (&v[0] + 1)  == (char*)&v[0] + sizeof(v[0]) );

    /*whereas adding 1 to &v increments the pointer by sizeof v (==5 * 4)*/

    assert ( (void*) (&v + 1)  == (char*)&v[0] + sizeof(v) );

    puts("success");
    return 0;
}