Search code examples
c++arraysc++11sizeofimplicit-conversion

How do i handle this situation C++ sizeof problem


void f(int* b[])
{
    cout << sizeof(*b) << endl;
}

int main()
{
    int x[4] = {1, 2, 3, 4};
    int* a[] = {&x[0], &x[1], &x[2], &x[3]};

    cout << sizeof(a) << endl;

    f(a);
}

The program is output firstly 32 (in main) and 8 (in function)

How do i handle this situation?


Solution

  • If I have understood correctly you are trying to get the size of the passed array in the function.

    Do it the following way

    template <size_t N>
    void f( int* ( &b )[N] )
    {
        cout << sizeof( b ) << endl;
    }
    

    In C you should declare the function with one more parameter like

    void f(int* b[], size_t n )
    {
        printf( "%zu\n", n * sizeof( *b ) );
    }
    

    and call it like

    f(a, sizeof( a ) / sizeof( *a ) );
    

    Such an approach you can use also in C++.