c++arrayssizeof

Size of array in C++


Consider the following code:

int main()
{
    int arr[] = {1,2,3,7,8};
    std::size_t size = sizeof arr;
    std::cout << size << '\n';
}

I know that the above code will print the size of the array which is sizeof (int) ✕ 5 (20 bytes on my system with 4-byte int).

I have a small doubt in this: arr is a pointer to the first element in the array and the size of a pointer on my system is 4 bytes so why it does not print 4?

Even when we dereference arr and print it, the first element in the array will be printed.

cout << *arr;

So how does this sizeof operator work in case of arrays??


Solution

  • sizeof(arr) is one of those instances where arr does not decay to a pointer type.

    You can force pointer decay by using the unary plus operator:

    std::size_t/*a better type*/ size = sizeof(+arr);