-2
using namespace std;
int main( )
{
    int arr[ 5 ] = { 1 , 2 , 3 , 4 , 5 } ;
    cout << sizeof( arr ) << endl ;
    cout << sizeof( &arr ) << endl ;
    return 0 ;
}

why do we get answer 4 for sizeof( &arr) ,if &arr is a pointer to array why are we getting size 4 when size is 5

RoCkEt
  • 7
  • 1
  • Pointer on a platform has fixed size, it does not matter where it points to (pointers to regular types, not members or functions) – Slava Feb 09 '21 at 03:56
  • Not sure there's an existing answer that explains this well, but https://stackoverflow.com/questions/3397098/pointer-array-and-sizeof-confusion is close. – user202729 Feb 09 '21 at 03:58
  • This may help: https://en.cppreference.com/w/cpp/language/sizeof – Eljay Feb 09 '21 at 03:59
  • 4
    The size of a pointer to an array doesn't depend on the size of the array. – David Schwartz Feb 09 '21 at 04:10
  • 2
    What makes you think that the size of an address and the number of elements in an array should be the same? – user207421 Feb 09 '21 at 04:18
  • Array is not a pointer. Sometimes, it behaves the same way, but it is different language entity. Don't use `sizeof` for getting the number of array elements. Use [`std::size`](https://en.cppreference.com/w/cpp/iterator/size) library function instead (C++17+; pre-C++17, it's very easy to write one manually). – Daniel Langr Feb 09 '21 at 05:30
  • [How does sizeof know the size of array?](https://stackoverflow.com/q/27518251/995714), [Why `sizeof(array)` and `sizeof(&array[0])` gives different results?](https://stackoverflow.com/q/17320207/995714) – phuclv Feb 09 '21 at 09:38

1 Answers1

1

Difference is that arr is an array, while &arr is a pointer to the array. Compare to:

#include <iostream>
using namespace std;

int main( )
{
    int arr[5] = { 1, 2, 3, 4, 5 } ;  // array of 5 integers
    int (&ref_arr)[5] = arr;          // reference to array of 5 integers
    int (*ptr_arr)[5] = &arr;         // pointer to array of 5 integers

    cout << "array size  "   << sizeof(arr)  << " = " << sizeof(ref_arr) << endl;
    cout << "pointer size  " << sizeof(&arr) << " = " << sizeof(ptr_arr) << endl;

    return 0 ;
}

Possible output (for implementations with 32b integers and 64b pointers):

array size  20 = 20
pointer size  8 = 8
dxiv
  • 16,984
  • 2
  • 27
  • 49
  • 1
    +1 I didn't know the size of the `&arr` and the pointer to array `ptr_arr` could be equal by using the pointer to array assignment. This cleared my idea. – Rohan Bari Feb 09 '21 at 05:50
  • if &arr and ptr_arr are same i.e a pointer to array of 5 integer why *(&arr + 1 ) gives us the wrong output while *( arr + 1 ) gives us the correct output – RoCkEt Feb 09 '21 at 07:55
  • @RoCkEt `arr` decays to an `int *` while `&arr` is an `int (*)[5]` i.e. pointer to an array of 5 ints. The `+1` pointer arithmetic is different between the two, `*(arr + 1)` is simply `arr[1]` while `*(&arr + 1)` is an out of bounds access past the end of `arr`. – dxiv Feb 09 '21 at 08:05