-1

Given the following code what is the difference between ptr and ptr2? because size of v is 20 whereas size of &v[0] is 4. Why does this even work? Why not a third pointer like ptr* = &v. All of these have the same base address but what is the difference between first... I'm confused. And it gets even worse when using 2d arrays. Thank you for your help!

#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;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
M. Alex
  • 49
  • 1
  • 1
  • 5
  • Ohhh.. I missed it, why it is tagged with C? It's simply C++, as it appears. – Sourav Ghosh Jun 05 '17 at 10:47
  • There is no difference between `ptr` and `ptr2`. You never use them after initializing them either so it is not clear to me what you are asking. – M.M Jun 05 '17 at 10:48

2 Answers2

1

In the context of int *ptr = v;, the array v decays to &v[0]. In the context of sizeof(v), it's still an array.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
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;
}
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • Ok, thanks. One more question though. How can i alocate something like this with new operator: int(*p)[5] = new of what? – M. Alex Jun 05 '17 at 12:07