Why function does not know the array size?

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

If I write

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

        
相关标签:
8条回答
  • 2021-01-26 21:43

    The function does not know the array size in your example because you took explicit steps to convert your array to pointer type, thus completely stripping the function parameter of its original array nature. Once again, you yourself took deliberate steps to make sure that the function does not know the size of the array. Under these circumstances, it is rather strange to see you ask the question about why the function doesn't know the array size.

    If you what the function to receive its argument as an array, you have to pass it as an array, not as a mere pointer, and declare the corresponding function parameter accordingly. Arrays in C++ cannot be passed "by value", which means that you'll have to pass it "by reference", as one possibility

    void func(int (&a)[100])
    {
      cout << sizeof a / sizeof a[0] << endl;
    }
    
    0 讨论(0)
  • 2021-01-26 21:54

    sizeof returns the size of the type. In the second example, func( int *a ), a is a pointer and sizeof will report it as such. Even if you did func( int a[100] ), a would be a pointer. If you want the size of the array in func, you must pass it as an extra argument.

    0 讨论(0)
提交回复
热议问题