Search code examples
c++arrayspointersparameter-passingsizeof

Sizeof array passed as parameter of function


Let's consider the following code:

#include <iostream>
using namespace std;

void foo(int * arr)
{
    cout << sizeof(arr) << endl;
}

int main()
{
    int arr[3] = {1, 2, 3};
    cout << sizeof(arr) << endl;
    foo(arr);
}

Since array name decay into pointer to its first element, why does sizeof(arr) inside foo() returns 8 instead of 4?


Solution

  • In most cases the size of a pointer is 8 bytes. In your system that is the size of the pointer.

    Note that the size of the pointer, and you probably know this, is not the size of the object it points or the size of the type of object.

    The size of a pointer depends on several factors, like the CPU architecture, compiler or Operating System.

    The way it usually works is if the system is 16-bit, the of size pointers is 2 bytes, if the system is 32-bit, the size is 4 bytes, if it is 64-bit, it's 8 bytes.