Why function does not know the array size?

后端 未结 8 2153
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-26 21:04

If I write

int main()
{
    int a[100] = {1,2,3,4,};
    cout<

        
8条回答
  •  隐瞒了意图╮
    2021-01-26 21:34

    When passing your array as a parameter to a function taking a pointer, the array decays as a pointer.

    void bar(int *a)
    {
        std::cout << sizeof(a) << std::endl; // outputs "4" (on a 32 bit compiler)
    }
    
    void foo()
    {
        int a[100] ;
        std::cout << sizeof(a) << std::endl; // outputs "400" (on a 32 bit compiler)
        bar(a);
    }
    

    So perhaps the solution is to provide a correct function taking a reference to an array as a parameter :

    template 
    void bar(int (&a)[T_Size])
    {
        std::cout << T_Size << std::endl;    // outputs "100" (on ALL compilers)
        std::cout << sizeof(a) << std::endl; // outputs "400" (on a 32 bit compiler)
    }
    
    void foo()
    {
        int a[100] ;
        std::cout << sizeof(a) << std::endl; // outputs "400" (on a 32 bit compiler)
        bar(a);
    }
    

    Of course, the function must be templated.

提交回复
热议问题