Why function does not know the array size?

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

If I write

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

        
8条回答
  •  滥情空心
    2021-01-26 21:43

    You get 400 the first time because you are passing only sizeof(a), not sizeof(a)/sizeof(a[0]), to cout. You need to wrap that calculation with parenthesis to get the correct value outputted, ie:

    cout << (sizeof(a)/sizeof(a[0])) << endl;
    

    For the second time, you should be getting 2, 4, or 8 (depending on architecture), definately not 400, since you are essentially outputting this:

    cout << sizeof(int*) << endl;
    

    Where the size of a generic pointer is always a fixed value.

提交回复
热议问题