为什么函数不知道数组大小?

Nar*_*rek 1 c++ pointers function sizeof

如果我写

int main()
{
    int a[100] = {1,2,3,4,};
    cout<<sizeof(a)/sizeof(a[0])<<endl; //a is a pointer to the first elem of array, 
                                        //isn't it
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到400!

如果我写

void func(int*a);

int main()
{
    int a[100] = {1,2,3,4,};
    func(a);
    return 0;
}

void func(int *a)
{
     cout<<sizeof(a)/sizeof(a[0])<<endl; //a is a pointer to the first elem of array
}
Run Code Online (Sandbox Code Playgroud)

然后我得到1!

那么为什么函数不知道数组大小呢?

Pau*_*l R 5

传递给函数时,数组会衰减到指针,所以你得到的只是指针的大小.