Search code examples
c++arrayssizeof

Getting different sizeof values of the same array in main and in a function


In the following code, when I print sizeof(arr) in main(), I get output 32. However when I send the same array to a function print() and print out sizeof(arr), I get 8.

My question is, shouldn't they both be 8, because arr is a pointer to the first element in both cases?

Code:

#include <iostream>

using namespace std;

void print(int arr[])
{
    cout << "from function print(): " << sizeof(arr);
}

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

    cout << "from main: " << sizeof(arr) << endl;

    print(arr);

    return 0;
}

Output:

main.cpp:8:46: warning: ‘sizeof’ on array function parameter ‘arr’ will return size of ‘int*’ [-Wsizeof-array-argument]                       
main.cpp:5:20: note: declared here                                                                                                            
from main: 32                                                                                                                                 
from function print(): 8                                                                                                                      
                                                                                                                                              
...Program finished with exit code 0                                                                                                          
Press ENTER to exit console.  

Solution

  • My question is, shouldn't they both be 8, because arr is a pointer to the first element in both cases?

    An array name is not a pointer. In main, where arr is declared and initialized you will get the real size of arr, which in your case is 32 bytes, 8 times(the number of elements) 4(your system int type size).

    sizeof is able to calculate the total size of the array because it's an array type, this is mandated by the C++ standard:

    [expr.sizeof]

    [...] When [sizeof is] applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.

    In

    void print(int arr[]){/*...*/}
    

    You're right, the int arr[] argument will decay to a pointer to arr, so sizeof(arr) is the size of the pointer, sizeof is not able to find the size of an object pointed by the pointer passed to it as an argument, it will render the size of the pointer instead, which in your system is 8 bytes, as it usually is in a 64 bit system.

    As you are using an expression instead of a type you can remove the parenthesis and use sizeof arr only.

    On a side note, using namespace std; is not advised.