Kakarot_7
Kakarot_7

Reputation: 342

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??

Upvotes: 1

Views: 5007

Answers (3)

Picaud Vincent
Picaud Vincent

Reputation: 10982

To complete the answers you can also get the number of elements using C++11's std::extent

On my machine:

#include <iostream>
#include <type_traits>

int main()
{
  int arr[] = {1,2,3,7,8};

  std::cout << sizeof(arr) << "\n";
  std::cout << sizeof(+arr) << "\n";
  std::cout << std::extent<decltype(arr)>::value << "\n";
}

prints:

20
8
5

From @eerorika comment:

If you use C++17 you can also use std::size

std::cout << std::size(arr); // prints 5

Upvotes: 2

eerorika
eerorika

Reputation: 238311

arr is a pointer to the first element in the array

This is a wrong assumption. arr is not a pointer. It is an array of 5 integers.

so why it does not print out 4 in the console?

Because that is not the size of arr in bytes.

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

You get the size of the type in bytes. Same as every other type.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234655

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);

Upvotes: 4

Related Questions